RestTemplate cannot get JSONObject

I cannot directly get JSONObject, this code works:

RestTemplate restTemplate = new RestTemplate(); String str = restTemplate.getForObject("http://127.0.0.1:8888/books", String.class); JSONObject bookList = new JSONObject(str); 

but this code does not:

 JSONObject bookList = restTemplate.getForObject("http://127.0.0.1:8888/books", JSONObject.class); 

What could be the problem? It gives no errors, but I have an empty JSONObject at the end.

my pom.xml:

 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>library-client</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>LibraryClient</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 

and I have to add a little more detailed information that you can see when I use the line to create inbetween. and a little more detail, maybe I should remove my pom.xml to reduce the amount of code in this question, would that make sense? | Okay yet?

+5
source share
1 answer

RestTemplate will use reflection to create the resulting object.

When you use restTemplate.getForObject , it will try to use the default constructor for the class you are passing in, and then try to fill in all its fields. In this case, it does not know how to create a JSONObject

To do this, you must:

  • use your own HttpMessageConverterExtractor
  • use the second approach JSONObject bookList = new JSONObject(str);
+5
source

Source: https://habr.com/ru/post/1263319/


All Articles