简体   繁体   中英

Converting Json File to ArrayList<Custom>

I'm having problem in converting Json file to Arraylist, I use 2 methods:

This is my JSON:

[
   {
      "NICN":"1",
      "DOB":"Thu Jan 01 00:00:00 SRET 1998",
      "Gender":77,
      "Module":[
         {
            "Module ID":"2",
            "Assignment Score":0,
            "Exam Score":0
         },
         {
            "Module ID":"3",
            "Assignment Score":0,
            "Exam Score":0
         },
         {
            "Module ID":"4",
            "Assignment Score":0,
            "Exam Score":0
         }
      ],
      "DOJ":"Wed Jan 01 00:00:00 SRET 1997",
      "Nationality":"1",
      "StudentID":"S000000",
      "Name":"James"
   }
]

This is the first Method: JSON parsing:

ArrayList<Student> CurStudentList = new ArrayList<>();
    Student CurStudentObj = new Student();

    //Read From File
    try {
        JSONArray baseJSONResponse = new JSONArray("JSON1.json");

        for (int i = 0; i < baseJSONResponse.length(); i++) {
            JSONObject StudentObj = baseJSONResponse.getJSONObject(i);
            CurStudentObj.setmStudentID(StudentObj.getString("StudentID"));
            CurStudentObj.setmName(StudentObj.getString("Name"));
            CurStudentObj.setmGender(StudentObj.getString("Gender").charAt(0));
            String TempDOB = (StudentObj.getString("DOB"));
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MM dd HH:mm:ss z yyyy");
            try {
                Date dDOB = sdf.parse(TempDOB);
                CurStudentObj.setmDateOfBirth(dDOB);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            CurStudentObj.setmNICN(StudentObj.getString("NICN"));
            String TempDOJ = (StudentObj.getString("DOJ"));
            try {
                Date dDOJ = sdf.parse(TempDOJ);
                CurStudentObj.setmDateJoined(dDOJ);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            CurStudentObj.setmGender(StudentObj.getString("Gender").charAt(0));
            JSONArray array = StudentObj.getJSONArray("Module");
            for (int a = 0; a < 3; a++) {
                JSONObject ArrayOne = new JSONObject();
                CurStudentObj.setmModules((ArrayOne.getString("Module ID")), Integer.parseInt(ArrayOne.getString("Assignment Score")), Integer.parseInt(ArrayOne.getString("Exam Score")));
            }
    }

This is the error occurred, may be wrong parsing:

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
    at org.json.JSONObject.<init>(JSONObject.java:184)
    at org.json.JSONObject.<init>(JSONObject.java:310)
    at Register.Student(Register.java:30)
    at Main.main(Main.java:22)

I'm currently would like to read my Json File and Store inside my program ArrayList. So that I can edit the information, which can update by writing to file again.

I search online for another method that uses Gson, you wont need to parse, just add into the Arraylist but it only works on ArrayList<String> . Not Custom ArrayList<Student>

The string you give into the JSONArray() -Constructor must be a json string. Currently you just passed the file name.

To fix this just implement following steps:

  1. Get your File
  2. Read it's lines into 1 single string
  3. Pass that string to JSONArray() -Constructor

You can use a Json parser. Because now the compiler thinks "JSON1.json" is the json string while it's just the file name.

Try this when creating your json object instead :

    JSONParser parser = new JSONParser();

    Object obj = parser.parse(new FileReader("yourFilePath"));

    JSONObject jsonObject =  (JSONObject) obj;

Then you'll have your entire object i think.

EDIT :

After that you'll have your whole json object, if you still want the Json String to pass to the JSONArray method you can get it by the toString() method on the JSON Object.

Instead of pass the filename to the JSONArray() you have to read in the file and convert it to a string like that:

//Read the stream
InputStream is = new FileInputStream(jsonFilename);

//Convert to string
String jsonTxt = IOUtils.toString(is);

//Create JSONArray from read JSON string
JSONArray arr = new JSONArray(jsonTxt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM