0

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[]
4
  • Try changing this SomeObject[] objectsList = gson.fromJson(jsonObject.toString(), SomeObject[].class) to SomeObject[] objectsList = gson.fromJson(jsonObject.toString(), SomeObject.class) Commented Jan 13, 2018 at 6:19
  • your json is not list of objects, but object with 2 properties or Map<String, SomeObject> Commented Jan 13, 2018 at 6:22
  • Your json is not an array? Commented Jan 13, 2018 at 6:25
  • Your json string should have [] without property names obj_1 and obj_2 but just the actual object and it’s properties k1..k3 to be a list of objects else it’s is an object with 2 properties obj_1 and obj_2. On same note k1 is int so it’s value will be without double quotes Commented Jan 13, 2018 at 6:40

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using an online api to get data and that;s the format it's giving me in. Will i have to manually edit the json string so it's in that format to achieve this?
If the API returns only 2 objects (obj_1 and obj_2) then better read the given JSON string as an JSON Object and extract each property (obj_1 and obj_2) as SomeObject and then form an array of SomeObject.
0

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

Comments

0

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.

Comments

0

Why not create an ArrayList of JSONObjects?

ArrayList <JSONObject> objectsList = new ArrayList<JSONObject>();
objectsList .add(jsonObject);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.