如何使用google gson库将内部对象的json对象反序列化为单个java对象?

时间:2015-09-06 07:29:06

标签: json gson

我有以下json文件:

{
  "sqldb": [
    {
      "name": "mydb",
      "label": "sqldb",
      "plan": "sqldb_free",
      "credentials": {
        "port": 50000,
        "db": "SQLDB",
        "username": "xxxxxxx",
        "host": "75.126.155.92",
        "hostname": "75.126.155.92",
        "jdbcurl": "jdbc:db2://75.126.155.92:50000/SQLDB",
        "uri": "db2://xxxxxxx:xxxxxxx@75.126.155.92:50000/SQLDB",
        "password": "xxxxxxx"
      }
    }
  ]
}

该对象具有以下结构:sqldb个对象的列表,其中包含内部credentials个对象。如何通过Google Gson library将其解析为单个sqldb对象?我的意思是可以使用gson的注释创建, Java Object 如下:

public class VcapObject{
    private String name;
    private String label;
    private String plan;
    private String port;
    private String db;
    private String username;
    private String host;
    private String hostname;
    private String jdbcurl;
    private String uri;
    private String password;
}

将填写:

 VcapObject vcapObject = gson.fromJson(vcapString, VcapObject.class);

例如?

2 个答案:

答案 0 :(得分:0)

要删除内部credentials对象,您需要一个自定义This answer,它将字段从内部类复制到外部类。您可以采取一些不同的策略,但这里有一个修改JSON树并将其反馈给Gson的策略。

public class VcapDeserializer implements JsonDeserializer<VcapObject> {

    private static final String MERGE_FIELD = "credentials";
    final private Gson gson;

    public VcapDeserializer() {
        gson = new Gson();
    }

    @Override
    public VcapObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if(json.isJsonObject()) {
            JsonObject jsonObject = json.getAsJsonObject();
            if(jsonObject.has(MERGE_FIELD)) {
                // We have the object, get all the fields
                JsonObject mergeObject = jsonObject.get(MERGE_FIELD).getAsJsonObject();
                Set<Map.Entry<String, JsonElement>> entries = mergeObject.entrySet();
                for(Map.Entry<String, JsonElement> entry : entries) {
                    // Copy property to top level object
                    jsonObject.add(entry.getKey(), entry.getValue());
                }
                // now that we have copied the fields, remove the nested object
                jsonObject.remove(MERGE_FIELD);
            }
            // Deserialize the top-level object
            return gson.fromJson(jsonObject, VcapObject.class);
         } else {
            // top level is supposed to be an object
            throw new IllegalStateException();
        }
    }
}

然后使用Gson -

创建自定义GsonBuilder实例
Gson gson = new GsonBuilder().registerTypeAdapter(VcapObject.class, new VcapDeserializer()).create();

注意 - 从您的问题来看,目前还不清楚是否要删除顶级包装器对象。我假设不是因为你没有说数组总是会返回一个元素。所以你仍然需要那个 -

public class SqlDbWrapper {
    List<VcapObject> sqldb;
}

然后使用 -

反序列化
    SqlDbWrapper sqlDbWrapper = gson.fromJson(jsonString, SqlDbWrapper.class);

答案 1 :(得分:-1)

您可以创建一个包含VcapObject集合的包装类,例如VcapList。然后你可以将VcapList作为类传递给fromJson。将方法添加到VcapList以获取第一个(如果不为空)。