簡體   English   中英

使用 Gson 動態解析 JSON 字段類型

[英]Resolve JSON field types dynamically using Gson

我有以下 API 響應:

{  
   "data":{  
      "categoryFields":[  
         {  
            "name":"brand",
            "label":"Marca", 
            "values":[  
               {  
                  "key":53,
                  "value":"Alfa Romeo"
               },
               {  
                  "key":55,
                  "value":"Audi"
               }
            ]
         },
         {  
            "name":"year",
            "label":"Año", ,
            "dataType":"select",
            "values":[  
               {  
                  "key":2017,
                  "value":2017
               },
               {  
                  "key":2016,
                  "value":2016
               }
            ]
         },

      ]
   }
}

好的,在第一個categoryField ,值是:

"key":53 INT,
"value":"Alfa Romeo", STRING

在第二個categoryField ,值是:

 "key":2017, INT
 "value":2017, INT

還有另一種類型:

 "key":"string", STRING
 "value":"String", STRING

我需要一個可以處理這些類型數據的類。 就像是:

public class Value {

    @SerializedName("key")
    @Expose
    private DYNAMIC_TYPE key;

    @SerializedName("value")
    @Expose
    private DYNAMIC_TYPE value; 

}

我怎樣才能做到這一點? 或者有一個 Gson 函數可以幫助我解決這個問題?

解決方案

public class CategoryValueDeserializer implements JsonDeserializer<CategoryValue> {
    @Override
    public CategoryValue deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();

        final JsonElement jsonKey = jsonObject.get("key");
        final String key = jsonKey.getAsString();

        final JsonElement jsonValue = jsonObject.get("value");
        final String value = jsonValue.getAsString();

        CategoryValue categoryValue = new CategoryValue();
        categoryValue.setKey(key);
        categoryValue.setValue(value);

        return categoryValue;

    }
}

//改造

 final Gson gson = new GsonBuilder()
                .registerTypeAdapter(Response.class, new CategoryValueDeserializer())
                .create();

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(END_POINT)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

這是一個有效的解決方案

首先創建一個像下面這樣的 POJO 類

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class KeyValuePair {
    @SerializedName("key")
    @Expose
    private String key;
    @SerializedName("value")
    @Expose
    private Object value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }
}

然后對於 Gson 正確序列化此類使用此代碼

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;

import java.lang.reflect.Type;

public class KeyValuePairDeserializer implements JsonDeserializer<KeyValuePair> {
    @Override
    public KeyValuePair deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        final JsonObject jsonObject = json.getAsJsonObject();

        final JsonElement jsonKey = jsonObject.get("key");
        final String key = jsonKey.getAsString();

        final JsonElement jsonValue = jsonObject.get("value");
        Object value = jsonValue.getAsString();
        if (jsonValue.isJsonPrimitive()) {
            JsonPrimitive jsonPrimitive = jsonValue.getAsJsonPrimitive();
            if (jsonPrimitive.isBoolean())
                value = jsonValue.getAsBoolean();
            else if (jsonPrimitive.isString())
                value = jsonValue.getAsString();
            else if (jsonPrimitive.isNumber()){
                value = jsonValue.getAsNumber();
            }
        }
        KeyValuePair categoryValue = new KeyValuePair();
        categoryValue.setKey(key);
        categoryValue.setValue(value);
        return categoryValue;
    }
}

像這樣用 Gson 注冊適配器

 Gson provideGson() {
        return new GsonBuilder()
                .registerTypeAdapter(KeyValuePair.class, new KeyValuePairDeserializer())
                .create();
    }

現在您可以使用這些 getter 方法訪問這些值

public String getString(String key) {
    return (String) value;
}

public int getInt(String key) {
    return ((Number) value).intValue();
}

public long getLong(String key) {
    return ((Number) value).longValue();
}

public float getFloat(String key) {
    return ((Number) value).floatValue();
}

public boolean getBoolean(String key) {
    return (boolean) value;
}

我總是有類似 BE 提供的dataType東西。 然后我可以在反序列化過程中基於它的值。 您也有dataType ,但僅適用於Int, Int大小寫。

好吧,我會做兩件事之一:

  • 與 BE 交談以針對每種不同的情況發送不同的dataType類型。 這對於具有許多參數和只有少數不同數據類型的類型很有用。 然后我用JsonDeserializer反序列JsonDeserializer到我需要的,有條件地 - 基於dataType
  • 如果您只有兩個值和三個可能的情況,則很容易通過isString和其他人進行檢查,如不同答案中所建議的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM