Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and Writing JSON file Java

Tags:

java

json

I'm trying to read a JSON file into a data structure so that I can count a bunch of elements.

The JSON file is of the format [{String, String, [], String } ... ]. Now in this array of objects, I need to find the relationship of the first string field (let's say association) to the array field (names of the members). I need to figure out how many associations each of these members belong to.

I'm currently using json-simple and this is how I've done it.

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);

Wondering if there is a simpler way in simple-json itself or if there are other libraries that better.

like image 402
rexbelia Avatar asked Apr 13 '26 12:04

rexbelia


2 Answers

Google gson is very simple to use both for encoding and decoding.

The simplest way is to fill an object by simply letting the engine fill the fields using reflection to map them to the content of the file as described here : the deserialization is just the call to gson.fromJson(json, MyClass.class); once you created your class.

like image 109
Denys Séguret Avatar answered Apr 16 '26 00:04

Denys Séguret


Seems like you're trying to do what they call Collections in Java. First I would look at your json model. Build a class that holds the properties you listed above. Then the code will look like this.

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

Hope this helps.

like image 22
JakeWilson801 Avatar answered Apr 16 '26 01:04

JakeWilson801



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!