我有一个像这样的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
。因为几乎我所有的代码都使用它,如何实现它?
正如在其他答案和评论中已经提到的那样,org.json.JSONObject
由于多种原因,您可能真的不想使用。但是,如果这对您来说是必须的,则只需创建您的org.json.JSONObject
-awareGson
实例。
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”}]
无论如何,我建议您重新设计映射模型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句