簡體   English   中英

使用Gson概括字段名稱

[英]Generalizing field names with Gson

我有一個看起來像這樣的JSON objext:

       {
               "isDefault": false,
               "someIndex":
               [
                   0
               ],
               "label": "Hello",
               "valueKindName": "someId",
               "value": 3,
               "conditions":
               {
                   "salesType":
                   [
                       1,
                       2
                   ],
                     "productType":
                   [
                       1,
                       5
                   ]
               }
           }

現在我的條件類看起來像這樣:

public class Conditions {

private List<Integer> salesType = new ArrayList<Integer>();
private List<Integer> productType = new ArrayList<Integer>();

}

這可行。 我想做的是概括我的課程,以便我可以將任何新類型設置為以下條件:

   "exampleType":
                   [
                       6,
                       9
                   ]

無需添加

private List<Integer> exampleType = new ArrayList<Integer>();

到我的Conditions.class

我想到了以下幾點:

public class Conditions {

    private ArrayList<Condition> conditions = new ArrayList<Condition>();
}

public class Condition {

    private String key;
    private ArrayList<Integer> values;
}

但是Gson當然不知道如何將JSON轉換為這種類型的數據結構。

任何幫助將高度贊賞:)

您可以注冊自己的轉換器。 它看起來像這樣:

public class ConditionConverter implements JsonSerializer<Condition>, JsonDeserializer<Condition>
{
  @Override
  public JsonElement serialize(Condition src, Type typeOfSrc, JsonSerializationContext context)
  {
    final JsonObject cond = new JsonObject()
    cond.add(src.key, context.serialise(src.values);

    return cond;
  }

  public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    // pick apart and make a condition again
  }
}

然后,向GsonBuilder注冊類型適配器:

builder.registerTypeAdapter(Condition.class, new ConditionConverter());

要分離對象,您需要使用JsonObject.entrySet() ,因為您事先不知道鍵名。 如果您采用這樣的JSON,您的工作將稍微容易一些:

{
  key: "exampleType",
  values: [ 42, 43 ]
}

暫無
暫無

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

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