java - 如何反序列化可能是字符串、对象或列表的 json/gson

标签 java android json gson

我有以下 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/

相关文章:

手机处于非 Activity 状态时的 Android 位置更新

android -/系统/bin/sh : adb: not found

javascript - 获取json数据到数组中

java - 如何将 JSON 字符串解析为 Jackson 中的 ObjectNode?

java - @Autowire 奇怪的问题

java - jar 文件和图像有问题

java - 范围报告report.endTest(test)方法?

java - 在 Java 8 中创建方法引用数组的简写方法?

android - "Don' t 在 Android Studio 中保留“Activity ”选项?

javascript - 将变量从 python 传递到 javascript