java 如何使用 Jackson / 其他库将 json 响应对象映射到首选格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35191510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:51:14  来源:igfitidea点击:

How to map json response object to a preferred format using Hymanson / other library?

javajsonspringspring-bootHymanson

提问by Great Question

I am getting the below JSON response format from a third party web service:

我从第三方 Web 服务获取以下 JSON 响应格式:

{
    "meta": {
        "code": 200,
        "requestId": "1"
    },
    "response": {
        "locations": [
            {
                "id": "1",
                "name": "XXX",
                "contact": {
                    phone: '123',
                    email: 'abc'
                },
                "location": {
                    "address": [
                        "Finland"
                    ]
                }
            },
            {
                // another location
            }
        ]
    }
}

And here is what I should return as a response from my own web service:

这是我应该从我自己的 Web 服务返回的响应:

[
    {
        "id": "1",
        "name": "XXX",
        "phone": '123',
        "address": "Finland"
    },
    {
        // another location
    }
]

What should I do? I've read some good stuff about Hymanson but there are only a few simple examples where you map some simple JSON obj as is to POJO. In my case, I need to remove a few nodes, and also traverse deeper down the hierarchy to get the nested value. This is my baby step so far in my spring boot app:

我该怎么办?我读过一些关于 Hymanson 的好东西,但只有几个简单的例子可以将一些简单的 JSON obj 原样映射到 POJO。就我而言,我需要删除一些节点,并深入层次结构以获取嵌套值。到目前为止,这是我在 Spring Boot 应用程序中的第一步:

    @GET
    @Path("{query}")
    @Produces("application/json")
    public String getVenues(@PathParam("query") String query){
        return client.target(url).queryParam("query",query).request(...).get(String.class)
    }

Any helps, pointers, recommendations are welcomed!

欢迎任何帮助、指点和建议!

采纳答案by nerdherd

You are using JAX-RS annotations instead of the Spring web service annotations. You can make this work, but I would recommend going with the default Spring annotations because those are all autoconfigured for you if you're using the spring boot starter dependencies.

您正在使用 JAX-RS 注释而不是 Spring Web 服务注释。您可以完成这项工作,但我建议您使用默认的 Spring 注释,因为如果您使用 spring boot starter 依赖项,这些注释都是为您自动配置的。

First thing - you need to create classes that are set up like the request and response. Something like this:

第一件事 - 您需要创建像请求和响应一样设置的类。像这样的东西:

public class ThirdPartyResponse {   
    MetaData meta;
    Response response;
}

public class Response {
    List<Location> locations;
}

public class MetaData {
    String code;
    String requestId;    
}

public class Location {
    String id;
    String name;
    Contact contact;
    LocationDetails location;
}

public class Contact {
    String phone;
    String email;
}

public class LocationDetails {
    List<String> address;
}

You can use Hymanson annotations to customize the deserialization, but by default it maps pretty logically to fields by name and the types you might expect (a JSON list named "locations" gets mapped to a List in your object named "locations", etc).

您可以使用 Hymanson 注释来自定义反序列化,但默认情况下,它按名称和您可能期望的类型非常合乎逻辑地映射到字段(名为“locations”的 JSON 列表映射到名为“locations”的对象中的列表等) .

Next you'll want to use a @RestControllerannotated class for your service, which makes the service call to the third party service using RestTemplate, something like:

接下来,您需要@RestController为您的服务使用一个带注释的类,它使用 来调用第三方服务RestTemplate,例如:

@RestController
public class Controller {

    @Value("${url}")
    String url;

    @RequestMapping("/path"
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Location> locations(@RequestParam String query) {

        // RestTemplate will make the service call and handle the 
        // mapping from JSON to Java object

        RestTemplate restTemplate = new RestTemplate();
        ThirdPartyResponse response = restTemplate.getForObject(url, ThirdPartyResponse.class);

        List<Location> myResponse = new List<>();            

        // ... do whatever processing you need here ...

        // this response will be serialized as JSON "automatically"
        return myResponse;
    }
}

As you can see, Spring Boot abstracts away a lot of the JSON processing and makes it pretty painless.

如您所见,Spring Boot 抽象了许多 JSON 处理,使其变得非常轻松。

Take a look at Spring's guides which are pretty helpful:

看看 Spring 的指南,这些指南非常有用:

Consuming a service with RestTemplate http://spring.io/guides/gs/consuming-rest/

使用 RestTemplate http://spring.io/guides/gs/sumption-rest/消费服务

Creating a web service using @RestController https://spring.io/guides/gs/rest-service/

使用 @RestController https://spring.io/guides/gs/rest-service/创建 Web 服务

回答by vineeth sivan

This can be done using google api HymansonFactory. Below is my suggested solution for this.

这可以使用 google api HymansonFactory来完成。以下是我为此建议的解决方案。

First you should create a pojo class corrosponding to the json data you are recieving and the json data to which you are trying to convert.

首先,您应该创建一个 pojo 类,对应于您正在接收的 json 数据和您尝试转换为的 json 数据。

Use google api client to map the keys to the pojo.

使用 google api 客户端将密钥映射到 pojo。

Below is the pojo classes corrosponding to the json data you are recieving.

下面是对应于您收到的 json 数据的 pojo 类。

 import com.google.api.client.util.Key;
 Class Response{
 @Key("locations")
 List<FromLocations> fromLocations;
 }


 import com.google.api.client.util.Key;
 Class FromLocations
 {
 @Key("id")
 String id;
 @Key("name")
 String name;
 @Key("contact")
 Contact contact;
 @Key("location")
 Location location;
 }  

Here Contact and Loaction will be a another classes using the same strategy;

这里 Contact 和 Loaction 将是使用相同策略的另一个类;

Below is the pojo corrosponding to the json to which you want to convert.

下面是对应于您要转换为的 json 的 pojo。

 Class ToLocations{
 String id;
 String name;
 String phone;
 String address;
 }

Now you can parse the requset containing the json objec to the fromLocations class as below.

现在您可以将包含 json 对象的请求集解析为 fromLocations 类,如下所示。

String responseMeta = response.parseAsString();
JSONObject queryJsonObject = new JSONObject(responseMeta);
if(queryJsonObject.has("locations")){
Response response = HymansonFactory.getDefaultInstance().fromString(responseMeta,Response.class);
List<FromLocations> fromLocationsList = response.getFromLocations();
}   

Next step is to iterate the list fromLocationsList and get the desired values from each FromLocations object and add it to the ToLocations object.

下一步是迭代 fromLocationsList 列表并从每个 FromLocations 对象获取所需的值并将其添加到 ToLocations 对象。

Next the ToLocations object can be add it to a list and convert it to json.

接下来可以将 ToLocations 对象添加到列表中并将其转换为 json。