简体   繁体   中英

Gson- Parsing a JSON array of JSON objects to ArrayList<org.json.JSONObject>

I have a JSON string like this:

{
  "r": [
    {
      "pic": "1.jpg",
      "name": "Name1"
    },
    {
      "pic": "2.jpg",
      "name": "Name2"
    },
    {
      "pic": "3.jpg",
      "name": "Name3"
    }
  ]
}

I want to parse to this POJO model:

public class Catalog {
    @SerializedName("r")
    @Expose
    private List<JSONObject> r = new ArrayList<JSONObject>();

    public List<JSONObject> getR() {
        return r;
    }

    public void setR(List<JSONObject> r) {
        this.r = r;
    }
}

I am parsing this way:

Catalog cat = new Gson().fromJson(jsonString,Catalog.class);

But finally am getting this json

{
  "r": [
    {
      "nameValuePairs": {}
    },
    {
      "nameValuePairs": {}
    },
    {
      "nameValuePairs": {}
    }
  ]
}

Please note that I don't want to use com.google.gson.JsonObject . I want to use org.json.JSONObject . How to achieve this because almost all of my code uses it?

I think you don't need JSONObject .

Try this

// is wrapped class for serialized json. 
public class JsonExample
{
    List<Catalog> r;
}

public class Catalog {
    private String pic;
    private String name;

    public String getPic() {
        return pic;
    }

    public String getName() {
        return name;
    }
}

JsonExample example = new Gson().fromJson(json, JsonExample.class);

Additional - using JSONObject

JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("r");

List<Catalog> cataList = new ArrayList<>();

for(int i = 0 ; i < arr.length() ; ++i)
{
    cataList.add(new Catalog(arr.getJSONObject(i)));
}

public class Catalog {
    private String pic;
    private String name;

    public Catalog(JSONObject obj) throws JSONException
    {
        pic = obj.getString("pic");
        name = obj.getString("name");
    }

    public String getPic() {
        return pic;
    }

    public String getName() {
        return name;
    }
}

As it was already mentioned in other answer and comments, you probably might not really want to use org.json.JSONObject for several reasons. But if it's a must for you, you just have to create your org.json.JSONObject -aware Gson instance.

final class JSONObjectJsonDeserializer
        implements JsonDeserializer<JSONObject> {

    // The implementation is fully thread-safe and can be instantiated once
    private static final JsonDeserializer<JSONObject> jsonObjectJsonDeserializer = new JSONObjectJsonDeserializer();

    // Type tokens are immutable values and therefore can be considered constants (and final) and thread-safe as well
    private static final TypeToken<Map<String, Object>> mapStringToObjectTypeToken = new TypeToken<Map<String, Object>>() {
    };

    private JSONObjectJsonDeserializer() {
    }

    static JsonDeserializer<JSONObject> getJsonObjectJsonDeserializer() {
        return jsonObjectJsonDeserializer;
    }

    @Override
    public JSONObject deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) {
        // Convert the input jsonElement as if it were a Map<String, Object> (a generic representation for JSON objectS)
        final Map<String, Object> map = context.deserialize(jsonElement, mapStringToObjectTypeToken.getType());
        // And forward the map to the JSONObject constructor - it seems to accept it nice
        return new JSONObject(map);
    }

}

Gson is designed thread-safe and does not need to be instantiated every time serialization or deserialization is necessary:

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapter(JSONObject.class, getJsonObjectJsonDeserializer())
        .create();

And finally:

final Catalog catalog = gson.fromJson(jsonString, Catalog.class);
out.println(catalog.getR());

with the following result:

[{"name":"Name1","pic":"1.jpg"}, {"name":"Name2","pic":"2.jpg"}, {"name":"Name3","pic":"3.jpg"}]

Anyway, I would suggest you to redesign your mappings model.

I think in your case, usage of gson library is not required at all. Only org.json can solve the entire problem.

Eg:

JSONObject json = new JSONObject(jsonString);

JSONArray jsonArray = json.getJSONArray("r");

List<JSONObject> jsonList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
  jsonList.add(jsonArray.getJSONObject(i));
}

Catalog catalog = new Catalog();        
catalog.setR(jsonList);

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