亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Gson處理對象或數組

Gson處理對象或數組

瀟湘沐 2019-11-14 15:15:28
我有以下課程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做到這一點嗎?
查看完整描述

3 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

謝謝您提供的三個杯子!


如果需要多個類型,則與泛型類型相同:


public class SingleElementToListDeserializer<T> implements JsonDeserializer<List<T>> {


private final Class<T> clazz;


public SingleElementToListDeserializer(Class<T> clazz) {

    this.clazz = clazz;

}


public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    List<T> resultList = new ArrayList<>();

    if (json.isJsonArray()) {

        for (JsonElement e : json.getAsJsonArray()) {

            resultList.add(context.<T>deserialize(e, clazz));

        }

    } else if (json.isJsonObject()) {

        resultList.add(context.<T>deserialize(json, clazz));

    } else {

        throw new RuntimeException("Unexpected JSON type: " + json.getClass());

    }

    return resultList;

    }

}

并配置Gson:


Type myOtherClassListType = new TypeToken<List<MyOtherClass>>() {}.getType();

SingleElementToListDeserializer<MyOtherClass> adapter = new SingleElementToListDeserializer<>(MyOtherClass.class);

Gson gson = new GsonBuilder()

    .registerTypeAdapter(myOtherClassListType, adapter)

    .create();


查看完整回答
反對 回復 2019-11-14
?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

建立三杯的答案,我有以下讓JsonArray直接反序列化為數組的方法。


static public <T> T[] fromJsonAsArray(Gson gson, JsonElement json, Class<T> tClass, Class<T[]> tArrClass)

        throws JsonParseException {


    T[] arr;


    if(json.isJsonObject()){

        //noinspection unchecked

        arr = (T[]) Array.newInstance(tClass, 1);

        arr[0] = gson.fromJson(json, tClass);

    }else if(json.isJsonArray()){

        arr = gson.fromJson(json, tArrClass);

    }else{

        throw new RuntimeException("Unexpected JSON type: " + json.getClass());

    }


    return arr;

}

用法:


    String response = ".......";


    JsonParser p = new JsonParser();

    JsonElement json = p.parse(response);

    Gson gson = new Gson();

    MyQuote[] quotes = GsonUtils.fromJsonAsArray(gson, json, MyQuote.class, MyQuote[].class);


查看完整回答
反對 回復 2019-11-14
  • 3 回答
  • 0 關注
  • 804 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號