如何将复杂对象映射到简单字段

时间:2013-07-29 14:17:37

标签: json data-binding jackson gson

我有一个类似于以下内容的JSON文档:

{
  "aaa": [
    {
      "value": "ewfwefew"
    }
  ],
  "bbb": [
    {
      "value": "ewfewfe"
    }
  ]
}

我需要将其反序列化为更干净的内容,例如:

public class MyEntity{
  private String aaa;
  private String bbb;
}

解包每个数组并在反序列化时提取“值”字段的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

@Tim Mac的回答是正确的,但您可以为MyEntity课程编写custom deserializer来使更优雅

它应该是这样的:

private class MyEntityDeserializer implements JsonDeserializer<MyEntity> {

  public MyEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {

    JsonObject rootObj = json.getAsJsonObject();

    String nid = rootObj 
                   .get("nid")
                   .getAsJsonArray()
                   .get(0)
                   .getAsJsonObject()
                   .get("value")
                   .getAsString();

    String uuid = rootObj 
                   .get("uuid")
                   .getAsJsonArray()
                   .get(0)
                   .getAsJsonObject()
                   .get("value")
                   .getAsString();

    MyEntity entity = new MyEntity(nid, uuid);

    return entity;
  }
}

然后你必须注册TypeAdapter

Gson gson = new GsonBuilder().registerTypeAdapter(MyEntity.class, new MyEntityDeserializer()).create();

最后你必须像往常一样解析你的JSON:

MyEntity entity = gson.fromJson(yourJsonString, MyEntity.class);

Gson会自动使用您的自定义反序列化器将您的JSON解析为MyEntity类。

答案 1 :(得分:2)

如果你不能改变你所获得的json,你可以考虑按原样对其进行反序列化,然后将其转换为更易于管理的东西吗?

public class TmpEntity {
    public Value[] nid {get;set;}
    public Value[] uuid {get;set;}
}

public class Value {
    public string value {get;set;}
}


public class MyEntity {
    public string nid {get;set;}
    public string uuid {get;set;}
}

var tmp = ...; //deserialize using javascriptserializer
var converted = tmp.Select(a => new MyEntity() 
{
    nid = a.nid.First().value,
    uuid = a.uuid.First().value
}