如何使用非列表格式的JSON对象在GSON中创建列表?

时间:2018-08-17 13:49:12

标签: java json gson

我正在尝试将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 个答案:

答案 0 :(得分:0)

您可以使用TypeAdapter将对象转换为对象列表,或者仅将org.springframework.web.HttpMediaTypeNotSupportedException 中的所有对象转换为@RequestMapping(value = "/v1/teste", method = RequestMethod.POST) public Saida teste(final @RequestBody(required = true) Object objeto) {} @EnableWebMvc @WebAppConfiguration @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class IntegracaoTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void teste() throws Exception { this.mockMvc.perform(post("/v1/teste") .contentType(MediaType.APPLICATION_JSON).content("{}")) .andDo(print()).andExpect(status().is(200)); } } <tx:annotation-driven /> <context:annotation-config /> <aop:aspectj-autoproxy /> <context:component-scan base-package="com.teste.*" /> <!-- Entity Manager --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceXmlLocation" value="classpath:persistence.xml" /> <property name="persistenceUnitName" value="teste" /> </bean> <!-- Transaction Manager --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <jpa:repositories base-package="com.teste.repositories"/> MockHttpServletRequest: HTTP Method = POST Request URI = /v1/teste Parameters = {} Headers = {Content-Type=[application/json]} Handler: Type = com.teste.rest.TesteController$$EnhancerBySpringCGLIB$$c0dc19e2 Async: Was async started = false Async result = null Resolved Exception: Type = org.springframework.web.HttpMediaTypeNotSupportedException ModelAndView: View name = null View = null Model = null FlashMap: MockHttpServletResponse: Status = 415 Error message = null Headers = {Accept=[application/octet-stream, */*, text/plain;charset=ISO-8859-1, */*, application/xml, text/xml, application/*+xml, application/x-www-form-urlencoded, multipart/form-data]} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] ,然后将其解析为cluster,像这样:

JsonArray

答案 1 :(得分:0)

我建议您可以构建POJO模型,然后在导入数据后进行转换。

dotnet ef migrations add 'somename' dotnet ef database update

stackoverflow/model/CoreNode.java

package stackoverflow.model; /** * CoreNode */ public class CoreNode { private String state; private boolean leader; private String core; private String node_name; private String base_url; public CoreNode() { super(); } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public boolean getLeader() { return this.leader; } public void isLeader(boolean leader) { this.leader = leader; } public String getCore() { return this.core; } public void setCore(String core) { this.core = core; } public String getNode_name() { return this.node_name; } public void setNode_name(String node_name) { this.node_name = node_name; } public String getBase_url() { return this.base_url; } public void setBase_url(String base_url) { this.base_url = base_url; } }

stackoverflow/model/Shard.java

然后在您的主要功能中,对每个集合使用package stackoverflow.model; import java.util.Map; /** * Shard */ public class Shard { private String range; private String state; private Map<String, CoreNode> replicas; public Shard() { super(); } public String getRange() { return this.range; } public void setRange(String range) { this.range = range; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public List<CoreNode> getReplicas() { return this.replicas; } public void setReplicas(List<CoreNode> replicas) { this.replicas = replicas; } } 结构。 (然后是Map<String, Shard>集合的结构)

然后,无论您希望将哪个地图作为列表,都可以进行操作(对于Map<String, Map<String, Shard>> for the generic而言)

Shard