2

たくさんの要素を数えることができるように、JSONファイルをデータ構造に読み込もうとしています。

JSONファイルの形式は[{String, String, [], String } ... ]。このオブジェクトの配列で、最初の文字列フィールド(たとえば関連付け)と配列フィールド(メンバーの名前)の関係を見つける必要があります。これらのメンバーのそれぞれがいくつの協会に属しているかを把握する必要があります。

私は現在json-simpleを使用していますが、これが私が行った方法です。

Object obj = parser.parse(new FileReader("c://Users/James McNulty/Documents/School/CMPT 470/Ex 4/exer4-courses.json"));

        JSONArray jsonArray = (JSONArray) obj;

        ArrayList<JSONObject> courseInfo = new ArrayList<JSONObject>();
        Iterator<JSONObject> jsonIterator = jsonArray.iterator();

        while (jsonIterator.hasNext()) {
            courseInfo.add(jsonIterator.next());
            count++;
            //System.out.println(jsonIterator.next());
        }
        //System.out.println(count);

        String course = "";
        String student = "";
        ArrayList<JSONArray> studentsPerCourse = new ArrayList<JSONArray>();
        for (int i=0; i<count; i++) {
            course = (String) courseInfo.get(i).get("course");
            studentsPerCourse.add((JSONArray) courseInfo.get(i).get("students"));
            System.out.println(course);
            System.out.println(studentsPerCourse.get(i));
        }

        ArrayList<String> students = new ArrayList<String>();
        for (int i=0; i<count; i++) {
            for (int j=0; j< (studentsPerCourse.get(i).size()); j++) {
                students.add((String) studentsPerCourse.get(i).get(j));
                //System.out.println(studentsPerCourse.get(i).get(j));
            }
            //System.out.println(student);
        }

        JSONObject object = new JSONObject();
        Map<String, Integer> studentCourses = new HashMap<String, Integer>();
        Set<String> unique = new HashSet<String>(students);
        for (String key : unique) {
            studentCourses.put(key, Collections.frequency(students, key));
            object.put(key, Collections.frequency(students, key));
            //System.out.println(key + ": " + Collections.frequency(students, key));   
        }

        FileWriter file = new FileWriter("c://Users/James McNulty/Documents/School/CMPT 470/Ex 4/output.json");
        file.write(object.toJSONString());
        file.flush();
        file.close();

        System.out.print(object);

simple-json自体にもっと簡単な方法があるのか​​、それとも他のより良いライブラリがあるのか​​疑問に思います。

4

4 に答える 4

3

Google gsonは、エンコードとデコードの両方に非常に簡単に使用できます。

最も簡単な方法は、ここで説明するように、リフレクションを使用してエンジンにフィールドを入力させ、ファイルのコンテンツにマップさせることでオブジェクトを入力することです。逆シリアル化はgson.fromJson(json, MyClass.class);、クラスを作成した後の呼び出しです。

于 2012-06-10T06:34:52.147 に答える
1

彼らがJavaでコレクションと呼んでいることをやろうとしているようです。まず、あなたのjsonモデルを見てみましょう。上記のプロパティを保持するクラスを作成します。そうすると、コードは次のようになります。

 public void parseJson(){
      // Read your data into memory via String builder or however you choose. 
     List<modelthatyoubuilt> myList = new ArrayList<modelthatyoubuilt>();
     JSONArray myAwarry = new JSONArray(dataString);
     for(int i = 0; i < myAwarry.size(); i++){
     JSONObject j = myAwarry.get(i); 
     modelthatyoubuilt temp = new modelthatyoubuilt();
     temp.setProperty(j.getString("propertyname");
     //do that for the rest of the properties
     myList.add(temp); 

 }

 public int countObjects(ArrayList<modelthatyoubuilt> s){
      return s.size(); 
 }

お役に立てれば。

于 2012-06-10T06:35:57.623 に答える
1
public class AccessData {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String USER_AGENT = "Mozilla/5.0";
        try {


            String url = "https://webapp2017sql.azurewebsites.net/api/customer";
            URL obj = new URL(url);
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            con.setRequestProperty("Content-Type", "application/json");

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes("{\"Id\":1,\"Name\":\"Kamlesh\"} ");
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());


        }catch (Exception ex) {
            System.out.print(ex.getMessage());

            //handle exception here

        } finally {
            //Deprecated
            //httpClient.getConnectionManager().shutdown(); 
        }
    }

}
于 2017-04-20T05:00:42.133 に答える
0

JSONを初めて使用する場合は、最初に以下の例を試してjsonファイルを作成し、そこにデータを書き込みます。

public class JSONWrite 

{

    public static void main(String[] args) 

    {
//      JSONObject class creates a json object

        JSONObject obj= new JSONObject();
//      provides a put function to insert the details into json object

        obj.put("name", "Dinesh");
        obj.put("phone", "0123456789");
        obj.put("Address", "BAngalore");

//      This is a JSON Array List where we Creates an array 

        JSONArray Arr = new JSONArray();

//      Add the values in newly created empty array 

        Arr.add("JSON Array List 1");
        Arr.add("JSON Array List 2");
        Arr.add("JSON Array List 3");

//      adding the array with elements to our JSON Object

        obj.put("Remark", Arr);

        try{

//          File Writer creates a file in write mode at the given location

            FileWriter file = new FileWriter(IAutoconstant.JSONLPATH);

//          Here we convert the obj data to string and put/write it inside the json file

            file.write(obj.toJSONString());
            file.flush();
        }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
}

上記のjsonファイルからデータを読み取るには、以下のコードを見つけてください

//JsonParserを使用してJSON文字列をJsonオブジェクトに変換します

    JSONParser parser= new JSONParser();

//以前に作成したファイル内のJSON文字列を解析します

    Object obj=parser.parse(new FileReader(IAutoconstant.JSONLPATH));

//Json文字列はJSONObjectに変換されました

    JSONObject jsonObject =(JSONObject)obj;

//キーを使用してJSONオブジェクトの値を表示します

    String value1 = (String) jsonObject.get("name");

    System.out.println("value1 is "+value1);

//注釈が配列であったため、JSONObjectをJSONArrayに変換します。

    JSONArray arrayobject=(JSONArray) jsonObject.get("Remark");

//イテレータは、リスト内の各要素にアクセスするために使用されます

    Iterator<String> it = arrayobject.iterator();

//配列に要素がある限り、ループは続行されます。

    while(it.hasNext())
            {
            System.out.println(it.next());
            }
}

jsonread.writeの概念を理解するのに役立つことを願っています

于 2018-08-29T06:58:51.867 に答える