2012-06-10 225 views
3

我正在嘗試將JSON文件讀入數據結構,以便可以計算一堆元素。讀取和寫入JSON文件Java

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本身中是否有更簡單的方法,或者是否有更好的其他庫。

回答

3

Google gson使用非常簡單,既用於編碼和解碼。

最簡單的方法是通過簡單地讓引擎使用反射來填充字段以將它們映射到文件的內容爲described here:反序列化只是在創建類時調用gson.fromJson(json, MyClass.class);

1

好像你正在嘗試在Java中調用Collections。首先我會看看你的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(); 
} 

希望這會有所幫助。

+0

感謝您的輸入傢伙。我想我以我自己的方式計算出來,但是我無法將結果寫入JSON文件。 – rexbelia

0
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(); 
    } 
} 

}