Home Convert JSON String to List of Java Objects
Reply: 5

Convert JSON String to List of Java Objects

Zer0
1#
Zer0 Published in 2018-01-13 06:17:36Z

I have a simple JSON string in the format of:

{
  "obj_1": {
    "k1": "v1",
    "k2": "v2",
    "k3": "v3"
  },
  "obj_2": {
    "k1": "v1",
    "k2": "v2",
    "k3": "v3"
  }
}

And a class to represent each JSON object like so:

public class SomeObject {

public int k1;
public String k2;
public String k3;

public Constructor(int k1, String k2, String k3) {
    this.k1 = k1;
    this.k2 = k2;
    this.k3 = k3;
}

I want to read the JSON object into an array of those objects without having to loop using while loops as this takes a really long time.

JSONObject jsonObject = new JSONObject(jsonString);
SomeObject[] objectsList = gson.fromJson(jsonObject.toString(), SomeObject[].class);

The main idea is to populate each JSON object into the Java Class then into an array of SomeObject. This way inside the array i will have access to each object and access the properties using methods.

I end up getting an error message:

can't make objects of type SomeObject[]
JRG
2#
JRG Reply to 2018-01-13 07:32:43Z

Your input string should be as follows to qualify for a list of SomeObject

{
    [{
            "k1": 1,
            "k2": "v2",
            "k3": "v3"
        }, {
            "k1": 2,
            "k2": "v2",
            "k3": "v3"
        }
    ]
}

Below code should work ..

JSONObject jsonObject = new JSONObject(jsonString);
SomeObject[] objectsList = gson.fromJson(jsonObject.toString(), SomeObject[].class);

For given JSON String here you can handle this way (add toString() to SomeObject for displaying it)...

import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class TestClass {

    public static void main(String[] args) {
        List<SomeObject> list = new LinkedList<SomeObject>();
        String jsonString = "{\"obj_1\":{\"k1\":1,\"k2\":\"v2\",\"k3\":\"v3\"},\"obj_2\":{\"k1\":2,\"k2\":\"v2\",\"k3\":\"v3\"}}";
        Gson gson = new Gson();
        JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            // note entry.getKey() will be obj_1, obj_2, etc.
            SomeObject item = gson.fromJson(entry.getValue().getAsJsonObject(), SomeObject.class);
            list.add(item);
        }
        System.out.println(list);
    }
}

Sample Run

[SomeObject [k1=1, k2=v2, k3=v3], SomeObject [k1=2, k2=v2, k3=v3]]

NOTE: the value of k1 must be a number and without quotes as k1 is declared as int in SomeObject

user5616998
3#
user5616998 Reply to 2018-01-13 07:10:37Z

Your JSON structure is a Map, if you want an array or list use [ { } , {} ] it is the structure in JSON for array or list

Dhruv Narayan Singh
4#
Dhruv Narayan Singh Reply to 2018-01-13 11:20:00Z

1.You should make your class like this for getter and setter:

public class SomeObject {

    public int k1;
    public String k2;
    public String k3;

    public int getK1() {
        return k1;
    }

    public String getK2() {
        return k2;
    }

    public String getK3() {
        return k3;
    }

    public void setK1(int k1) {
        this.k1 = k1;
    }

    public void setK2(String k2) {
        this.k2 = k2;
    }

    public void setK3(String k3) {
        this.k3 = k3;
    }
}

You can easily convert JSON string to JSONObject.After that make modal objecgt and set value to variables of modal object using following code:

 try {
          JSONObject jsonObjectData = new JSONObject(YOUR_JSON_STRING);
        SomeObject object = new SomeObject();
    object.setK1(1);
    object.setK2("test 1");
    object.setK3("test 2");
    List<SomeObject> objectList = new  ArrayList<>();
    objectList.add(object);
   }catch (JSONException e){
            e.printStackTrace();
  }
vikas kumar
5#
vikas kumar Reply to 2018-01-13 07:19:41Z

The JSON you have posted seems to be like the dynamic type i.e you don't have a fixed key for that you can't simply make-array. you have to traverse it manually.

do something like this if you are using GSON.

public ArrayList getArray(String json){
  ArrayList<SomeObject> list = new ArrayList<>();
  Gson gson = new Gson();
  JsonObject obj = new JsonParser().parse(json).getAsJsonObject();
  for(Map.Entry<String,JsonElement> entry:obj.entrySet()){
      //parse json 
     SomeObject some = gson.fromJson(entry.getValue().getAsJsonObject(), SomeObject.class); 
      //here add to list
      list.add(some);
  }
 return list;
}

Note: sample code not tested.

NancySchorr
6#
NancySchorr Reply to 2018-01-13 07:34:04Z

Why not create an ArrayList of JSONObjects?

ArrayList <JSONObject> objectsList = new ArrayList<JSONObject>();
objectsList .add(jsonObject);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30911 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO