我有以下 json
"notes": {"note": [
{
"content": "Having wisdom teeth removed.",
"from": "employee"
},
{
"content": "Get well soon",
"from": "manager"
}
]},
问题是价值也可以
"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;
}
}
现在,当整个事情以字符串的形式返回时,我被困住了……