Resttemplate handles nested complex return objects

Time:2021-4-7

This article will introduce how to useRestTempalteRequest interface, how to deal with complex return objects (object nesting exists).

withTencent location service reverse address resolutionAs an example, the code shows how to deal with complex return objects.

As shown in the figure below

Resttemplate handles nested complex return objects

The whole response result can be regarded as an object, which containsresultObject,resultIt also contains other objects. How to obtain and use such return values?

Here we will use theJava inner classThere are also a lot of information on the Internet. There is no additional explanation here.

The request code is as follows

RestTemplate http=new RestTemplate();
Result1 result=http.getForObject("https://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=this_is_your_key&get_poi=1",Result1.class);

The point isResult1.classHow to write.

... / / the header is introduced and omitted

Write like this, useRestTemplate.getForObjectCan help us to convert the return value to the correspondingPOJO Result1.classType object and complete the assignment action, you need to note that thelombokTo simplify the code, its role is to help generategetter,setterAs well as the constructor method, more information can be found by yourself.

Pay attention

If the inner class is not explicitly declared aspublic, which cannot be read from an object of an external class.

As shown in the figure below

...
public class Result{
        private String address;
        private FormattedAddress formatted_address;

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        class FormattedAddress{
            private String recommend;
            private String rough;
        }
    }
...

amongResultAddedpublicIdentification, andFormattedAddressNo, so when we make the following call

RestTemplate http=new RestTemplate();

This work adoptsCC agreementReprint must indicate the author and the link of this article

Wild ginseng in the city