Search code examples
simplejson

Convert JSONArray to Object?


I have the following JSON and I want to create an Contact object from it. How we can do that using

<dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
</dependency>

Here is the String

{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Contact","url":"/services/data/v40.0/sobjects/Contact/0037F000001rW9rQAE"},"Id":"0037F000001rW9rQAE","Name":"Chris Smith"}]}

I developed below code but how how to used JSONArray to get the details from it ?

JSONParser jsonParser = new JSONParser();
        Object obj = jsonParser.parse(value);
        JSONObject jsonObject = (JSONObject) obj;

        JSONArray jsonArray =  (JSONArray) jsonObject.get("records");
        System.out.println("~~~~~~~~~~~>>> "+jsonArray);


        List<Contact> contacts = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject rec = (JSONObject) jsonArray.get(i);
            Contact c = new Contact();
            c.setId(jsonArray.get(j).toString());

            contacts.add(jsonArray.get(j).toString());
        }

Solution

  • You can solve your issue like this but if you want to manage exceptions you should use the method getString(KEY), instead optString(KEY)

    List<Contact> contacts = new ArrayList<>();
    for (int i = 0; i < jsonArray.size(); i++) {
       JSONObject rec = (JSONObject) jsonArray.get(i);
       Contact c = new Contact();
       c.setId(rec.optString("Id"));
       c.setName(rec.optString("Name"));
       c.setAtributes(rec.optJSONObject("attributes"))
       contacts.add(rec);
    }