我有以下 json
"notes": {"note": [
{
"content": "Having wisdom teeth removed.",
"from": "employee"
},
{
"content": "Get well soon",
"from": "manager"
}
]},
问题是值(value)也可能是
"notes": "",
或
"notes": {"note": {
"content": "This is a test note.",
"from": "employee"
}},
并将其存储在这些
public class Notes
{
@SerializedName ("note")
public List<Note> note;
}
public class Note
{
@SerializedName ("content")
public String content;
@SerializedName ("from")
public String from;
}
我相信我通过这样做解决了不是数组而是单个对象的问题
public class Json {
private static Gson gson;
private static class MyNoteClassTypeAdapter implements JsonDeserializer<List<RequestsDTO.Note>> {
public List<RequestsDTO.Note> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<RequestsDTO.Note> vals = new ArrayList<RequestsDTO.Note>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
vals.add((RequestsDTO.Note) ctx.deserialize(e, RequestsDTO.Note.class));
}
} else if (json.isJsonObject()) {
vals.add((RequestsDTO.Note) ctx.deserialize(json,RequestsDTO.Note.class));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return vals;
}
}
public static Gson getGson()
{
if (gson == null)
{
Type ListType = new TypeToken<List<RequestsDTO.Note>>() {}.getType();
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(DateTime.class, new DateTimeSerializer());
builder.registerTypeAdapter(ListType, new MyNoteClassTypeAdapter());
gson = builder.create();
}
return gson;
}
}
现在,当整个事情以字符串形式返回时,我被困住了....
最佳答案
请引用下面的代码 fragment ,使用 Gson 库反序列化您的 json,无一异常(exception)。
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("note");
if(elem.isJsonArray()) { //**Array**
List<Note> notelist = gson.fromJson(elem.toString(), new TypeToken<List<Note>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), Note.class);
} else { //**String**
String note = elem.toString();
}
关于java - 如何反序列化可能是字符串、对象或列表的 json/gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282308/