我正在尝试将 JSON 对象转换为 POJO,理想情况下我会collection在我的cluster对象中有一个(的)对象列表。然而,JSON 模式不使用列表,它使用collection名称的映射,该映射未知且可能会更改。有没有办法使用 GSON 将其转换为 POJO 列表?有问题的 JSON:{ "responseHeader":{ "status":0, "QTime":333}, "cluster":{ "collections":{ "collection1":{ "shards":{ "shard1":{ "range":"80000000-ffffffff", "state":"active", "replicas":{ "core_node1":{ "state":"active", "core":"collection1", "node_name":"127.0.1.1:8983_solr", "base_url":"http://127.0.1.1:8983/solr", "leader":"true"}, "core_node3":{ "state":"active", "core":"collection1", "node_name":"127.0.1.1:8900_solr", "base_url":"http://127.0.1.1:8900/solr"}}}, "shard2":{ "range":"0-7fffffff", "state":"active", "replicas":{ "core_node2":{ "state":"active", "core":"collection1", "node_name":"127.0.1.1:7574_solr", "base_url":"http://127.0.1.1:7574/solr", "leader":"true"}, "core_node4":{ "state":"active", "core":"collection1", "node_name":"127.0.1.1:7500_solr", "base_url":"http://127.0.1.1:7500/solr"}}}}, "maxShardsPerNode":"1", "router":{"name":"compositeId"}, "replicationFactor":"1", "znodeVersion": 11, "autoCreated":"true", "configName" : "my_config", "aliases":["both_collections"] } }, "aliases":{ "both_collections":"collection1,collection2" }, "roles":{ "overseer":[ "127.0.1.1:8983_solr", "127.0.1.1:7574_solr"] }, "live_nodes":[ "127.0.1.1:7574_solr", "127.0.1.1:7500_solr", "127.0.1.1:8983_solr", "127.0.1.1:8900_solr"] }}
2 回答
忽然笑
TA贡献1806条经验 获得超5个赞
您可以使用 TypeAdapter 将您的对象转换为对象列表,或者只是将所有对象cluster放入 aJsonArray然后将其解析为 a List<Collection>,如下所示:
JsonArray jsonArr = new JsonArray();
JsonObject fullObj = new GsonBuilder().create().fromJson(jsonStr, JsonObject.class);
fullObj.getAsJsonObject("cluster")
.entrySet()
.forEach(col -> jsonArr.add(col.getValue()));
List<Collection> collections = gson.fromJson(jsonArr.toString(), Collection.class);
添加回答
举报
0/150
提交
取消