简体   繁体   English

将Complex Json映射到Pojo类

[英]Map Complex Json to Pojo Class

I am sending the following request (using Spring Boot) 我正在发送以下请求(使用Spring Boot)

 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);

response is the json object(i have ommitted lot of fields in json object) 响应是json对象(我​​在json对象中省略了很多字段)

{
    "customer": {
        "id": 100,
        "ci": {
            "lDb": "11",
            "localId": "1"
        },
        "cusdata": {},
        "rating": {
            "id": 3140,
            "dateTime": "2019-09-21 06:45:41.10",
            "rawData": {
                "seg": "XYZ",
                "seg2": "XYZ",
                "et": "XYZ_CORP",
                "CountryCodes": [
                    "IN"
                ],
                "doBusiness": "2017-09-20"
                ],
                ...

                ....
                ...
                ...



    "status": "SUCCESS"
}

I need to map the below fields to a Pojo Class 我需要将以下字段映射到Pojo类

1.localId 2.seg 3.seg2 4.status 1.localId 2.seg 3.seg2 4.status

How can i create the PojoClass such that those fields are mapped automatically 我如何创建PojoClass以便自动映射这些字段

So basically how will my PojoClass should look like? 所以基本上我的PojoClass应该是什么样子?

ResponseEntity<PojoClass> response = restTemplate.exchange(url, HttpMethod.GET, request, PojoClass.class);

I suggest that you use sites like http://www.jsonschema2pojo.org/ . 我建议您使用http://www.jsonschema2pojo.org/之类的网站 There, you can select many options on the right panel and adjust POJO you want to get from JSON schema. 在这里,您可以在右侧面板上选择许多选项,并调整要从JSON模式获取的POJO。

Your PojoClass has to follow the structure of the JSON that your are receiving and have the fields that your are interested (or all of them). 您的PojoClass必须遵循您正在接收的JSON的结构,并具有您感兴趣的字段(或所有字段)。

For the first level class: 对于头等舱:

public class PojoClass {
    private Customer customer;
    private String status;
    ...
}

Then, create a Customer class for the customer fields and create more classes for the rest of the fields: 然后,为客户字段创建一个Customer类,并为其余字段创建更多的类:

public class Customer {
    public String id;
    public CI ci;
    public CustData custData;
    ...
}

Create a custom class PojoClass 创建一个自定义类PojoClass

  public class PojoClass {
        private Integer id;
        private Object ci;
        private Object cusdata;
        private Object rating;
        private Object status;
    }

ResponseEntity<PojoClass> responseEntity = restTemplate.exchange(url,HttpMethod.GET,request,new ParameterizedTypeReference<PojoClass>(){
        });

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

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