Gson处理对象或数组

我有以下课程


public class MyClass {

    private List<MyOtherClass> others;

}


public class MyOtherClass {

    private String name;

}

我有可能看起来像这样的JSON


{

  others: {

    name: "val"

  }

}

或这个


{

  others: [

    {

      name: "val"

    },

    {

      name: "val"

    }

  ]

}

我希望能够MyClass对这两种JSON格式使用相同的格式。有办法用Gson做到这一点吗?


潇湘沐
浏览 730回答 3
3回答

慕沐林林

谢谢您提供的三个杯子!如果需要多个类型,则与泛型类型相同:public class SingleElementToListDeserializer<T> implements JsonDeserializer<List<T>> {private final Class<T> clazz;public SingleElementToListDeserializer(Class<T> clazz) {&nbsp; &nbsp; this.clazz = clazz;}public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {&nbsp; &nbsp; List<T> resultList = new ArrayList<>();&nbsp; &nbsp; if (json.isJsonArray()) {&nbsp; &nbsp; &nbsp; &nbsp; for (JsonElement e : json.getAsJsonArray()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resultList.add(context.<T>deserialize(e, clazz));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if (json.isJsonObject()) {&nbsp; &nbsp; &nbsp; &nbsp; resultList.add(context.<T>deserialize(json, clazz));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException("Unexpected JSON type: " + json.getClass());&nbsp; &nbsp; }&nbsp; &nbsp; return resultList;&nbsp; &nbsp; }}并配置Gson:Type myOtherClassListType = new TypeToken<List<MyOtherClass>>() {}.getType();SingleElementToListDeserializer<MyOtherClass> adapter = new SingleElementToListDeserializer<>(MyOtherClass.class);Gson gson = new GsonBuilder()&nbsp; &nbsp; .registerTypeAdapter(myOtherClassListType, adapter)&nbsp; &nbsp; .create();

波斯汪

建立三杯的答案,我有以下让JsonArray直接反序列化为数组的方法。static public <T> T[] fromJsonAsArray(Gson gson, JsonElement json, Class<T> tClass, Class<T[]> tArrClass)&nbsp; &nbsp; &nbsp; &nbsp; throws JsonParseException {&nbsp; &nbsp; T[] arr;&nbsp; &nbsp; if(json.isJsonObject()){&nbsp; &nbsp; &nbsp; &nbsp; //noinspection unchecked&nbsp; &nbsp; &nbsp; &nbsp; arr = (T[]) Array.newInstance(tClass, 1);&nbsp; &nbsp; &nbsp; &nbsp; arr[0] = gson.fromJson(json, tClass);&nbsp; &nbsp; }else if(json.isJsonArray()){&nbsp; &nbsp; &nbsp; &nbsp; arr = gson.fromJson(json, tArrClass);&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException("Unexpected JSON type: " + json.getClass());&nbsp; &nbsp; }&nbsp; &nbsp; return arr;}用法:&nbsp; &nbsp; String response = ".......";&nbsp; &nbsp; JsonParser p = new JsonParser();&nbsp; &nbsp; JsonElement json = p.parse(response);&nbsp; &nbsp; Gson gson = new Gson();&nbsp; &nbsp; MyQuote[] quotes = GsonUtils.fromJsonAsArray(gson, json, MyQuote.class, MyQuote[].class);
打开App,查看更多内容
随时随地看视频慕课网APP