【问题标题】:Deserializing JSON objects with variable structure, GSON反序列化具有可变结构的 JSON 对象,GSON
【发布时间】:2016-09-03 05:21:43
【问题描述】:

我正在尝试使用 GSON 反序列化具有以下结构的 JSON:

"FKeyColumn": [{
                "ForeignKeyColumns": {
                    "Id": "Id"
                },
                "ReferenceTable": "Expense_Group_Configurations"
            }],

"FKeyColumn": [{
                "ForeignKeyColumns": {
                    "Vid": "Id"
                },
                "ReferenceTable": "Expense_Group_Configurations"
            }]     

           ...

我不确定如何构造我的ForeignKeyColumns 类,因为它所代表的 JSON 对象包含任意键值对(除了始终命名为 ForeignKeyColumns 的对象之外没有设置结构)。如何使用 GSON 解析?

【问题讨论】:

    标签: json gson


    【解决方案1】:

    它需要一个自定义的 FKeyColumn 对象的反序列化器:

    public class FKeyColumnDeserializer implements JsonDeserializer<FKeyColumn> {
    
              public FKeyColumn deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
                  throws JsonParseException {
                final JsonArray jsonFKArray = json.getAsJsonArray();
                final FKeyColumn fkc = new FKeyColumn();
    
                for (int i = 0; i < jsonFKArray.size(); i++) {
                  final JsonObject fkObject = (JsonObject) jsonFKArray.get(i);
                  final String ReferenceTable = fkObject.get("ReferenceTable").getAsString();
                  final JsonObject ForeignKeyColumns = (JsonObject) fkObject.get("ForeignKeyColumns");
    
                  Set<Entry<String, JsonElement>> entrySet = ForeignKeyColumns.entrySet();
                  for(HashMap.Entry<String, JsonElement> entry : entrySet){
                      fkc.fkRefTableMap.put(entry.getKey(), ReferenceTable);
                  }
                }
    
    
                return fkc;
              }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多