繁体   English   中英

Gson-将JSON对象的JSON数组解析为ArrayList <org.json.JSONObject>

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

我有一个像这样的JSON字符串:

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

我想解析这个POJO模型:

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

我这样解析:

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

但最后我得到了这个json

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

请注意,我不想使用com.google.gson.JsonObject 我想使用org.json.JSONObject 如何实现这一点,因为我的几乎所有代码都使用它?

我认为你不需要JSONObject

尝试这个

// 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);

附加 - 使用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;
    }
}

正如在其他答案和评论中已经提到的那样,出于几个原因,您可能并不真的想要使用org.json.JSONObject 但是如果它对你来说是必须的,你只需要创建你的org.json.JSONObject Gson实例。

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的设计是线程安全的,每次需要序列化或反序列化时都不需要实例化:

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

最后:

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

结果如下:

[{“name”:“Name1”,“pic”:“1.jpg”},{“name”:“Name2”,“pic”:“2.jpg”},{“name”:“Name3”, “PIC”: “3.JPG”}]

无论如何,我建议你重新设计你的映射模型。

我认为在你的情况下,根本不需要使用gson库。 只有org.json可以解决整个问题。

例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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