简体   繁体   English

如何将2d json数组映射到pojo类?

[英]How can I map my 2d json array to a pojo classes?

I have a json structre as below 我有一个json structre如下

{
"components":
{
"metadata":[
   [
     {"component":2},{"component":9}
   ],
   [
     {"component":10},{"component":15}
   ]
 ]
}
}

And my POJO class is () 我的POJO课是()

public class Components {

private List<Metadata> metadata;
// Getters and setters
}

public class Metadata{  

private List<String> component;
// Getters and setters

} }

I am getting error in ObjectMapper as below: 我在ObjectMapper中遇到错误,如下所示:

"Can not deserialize instance of com.sections.metadata.Metadata out of START_ARRAY token"

Can anyone help me correcting my POJO class structure ? 谁能帮我纠正我的POJO类结构? Since the json is a 2D array, I have created two arrayLists, one in Component class and other in Metadata class. 由于json是2D数组,因此我创建了两个arrayLists,一个在Component类中,另一个在Metadata类中。

Thanks in advance ! 提前致谢 !

{
"components":
{
  "metadata":[
    [
      {"component":2},{"component":9}
    ],
    [
      {"component":10},{"component":15}
    ]
  ]
}
}

The above JSON doesnot correspond to the object structure that you specified. 上面的JSON与您指定的对象结构不对应。

  • In the components, there is no Array of 'metadata'. 在组件中,没有“元数据”数组。 Note that there are no '[]' around it. 请注意,它周围没有“ []”。
  • Inside metadata, there is an array of objects(or simply arrays) each of which has List of Strings, component 在元数据中,有一个对象数组(或简单的数组),每个对象都有字符串列表,组件

This is what you need: 这是您需要的:

public class ComponentsWrapper {

    private Components components;

    public Components getComponents() {
        return components;
    }

    public void setComponents(Components components) {
        this.components = components;
    }

    public static void main(String[] args) throws IOException, URISyntaxException {
        ObjectMapper objectMapper = new ObjectMapper();
        ComponentsWrapper components =
                objectMapper.readValue(<your JSON>),
                        ComponentsWrapper.class);


    }
}

class Components {

    private List<List<Component>> metadata;

    public List<List<Component>> getMetadata() {
        return metadata;
    }

    public void setMetadata(List<List<Component>> metadata) {
        this.metadata = metadata;
    }
}

class Component {

    private int component;

    public int getComponent() {
        return component;
    }

    public void setComponent(int component) {
        this.component = component;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM