Java 尝试使用 Spring Boot REST 从 POST 读取 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29313687/
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-08-11 07:46:02  来源:igfitidea点击:

Trying to use Spring Boot REST to Read JSON String from POST

javajsonrestspring-mvcspring-boot

提问by PacificNW_Lover

Am using the latest version of Spring Boot to read in a sample JSON via Restful Web Service...

我正在使用最新版本的 Spring Boot 通过 Restful Web 服务读取示例 JSON...

Here's my pom.xml:

这是我的 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"       
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/maven-v4_0_0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>myservice</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </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>org.springframework.data</groupId>
            <artifactId>spring-data-rest-webmvc</artifactId>
        </dependency>
        <dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Here's my web service code:

这是我的网络服务代码:

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/myservice")
public class BaseService {  

    @RequestMapping(value="/process", method = RequestMethod.POST)
    public void process(@RequestBody String payload) throws Exception {
        System.out.println(payload);
    }
}

When I invoke it using the following command:

当我使用以下命令调用它时:

curl -H "Accept: application/json" -H "Content-type: application/json" 
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process

I get this error message:

我收到此错误消息:

{"timestamp":1427515733546,"status":400,
 "error":"Bad Request",

"exception":
"org.springframework.http.converter.HttpMessageNotReadableException","
 message":
 "Could not read JSON: Can not deserialize instance of java.lang.String
  out of START_OBJECT token\n at 

 [Source: java.io.PushbackInputStream@8252f; line: 1, column: 1]; 
  nested    exception is com.fasterxml.Hymanson.databind.JsonMappingException:
  Can not deserialize instance of java.lang.String out of START_OBJECT token\n    
  at [Source: java.io.PushbackInputStream@8252f; line: 1, column: 1]",
  "path":"/myservice/process"

The only thing I am trying to do is pass in some valid JSON (as a string via curl) and to see if the String payload enters the process method as {"name":"value"}

我唯一想做的就是传入一些有效的 JSON(作为通过 curl 的字符串)并查看 String 负载是否以 {"name":"value"} 的形式进入 process 方法

What am I possibly doing wrong?

我可能做错了什么?

Thank you for taking the time to read this...

感谢您抽出时间来阅读...

采纳答案by Andrea

I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761

我认为使用 JSON 的最简单/方便的方法是使用类似于您的 JSON 的 Java 类:https: //stackoverflow.com/a/6019761

But if you can't use a Java class you can use one of these two solutions.

但是,如果您不能使用 Java 类,则可以使用这两种解决方案之一。

Solution 1:you can do it receiving a Map<String, Object>from your controller:

解决方案 1:您可以Map<String, Object>从控制器接收 a :

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object> payload) 
    throws Exception {

  System.out.println(payload);

}

Using your request:

使用您的请求:

curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process


Solution 2:otherwise you can get the POST payload as a String:

解决方案 2:否则您可以将 POST 有效负载作为String

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST,
    consumes = "text/plain")
public void process(@RequestBody String payload) throws Exception {

  System.out.println(payload);

}

Then parse the string as you want. Note that must be specified consumes = "text/plain"on your controller. In this case you must change your request with Content-type: text/plain:

然后根据需要解析字符串。请注意,必须consumes = "text/plain"在您的控制器上指定。在这种情况下,您必须使用以下命令更改您的请求Content-type: text/plain

curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \
-d '{"name":"value"}' http://localhost:8080/myservice/process

回答by Master Slave

The issue appears with parsing the JSON from request body, tipical for an invalid JSON. If you're using curl on windows, try escaping the json like -d "{"name":"value"}"or even -d "{"""name""":"value"""}"

问题出现在从请求正文解析 JSON 时,典型的无效 JSON。如果您在 Windows 上使用 curl,请尝试转义 json-d "{"name":"value"}"甚至-d "{"""name""":"value"""}"

On the other hand you can ommit the content-type header in which case whetewer is sent will be converted to your String argument

另一方面,您可以省略 content-type 标头,在这种情况下,发送的 whetewer 将转换为您的 String 参数

回答by S. Pan

To add on to Andrea's solution, if you are passing an array of JSONs for instance

要添加到 Andrea 的解决方案,例如,如果您要传递 JSON 数组

[
    {"name":"value"},
    {"name":"value2"}
]

Then you will need to set up the Spring Boot Controller like so:

然后你需要像这样设置 Spring Boot 控制器:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object>[] payload) 
    throws Exception {

    System.out.println(payload);

}

回答by Rusli Usman

To further work with array of maps, the followings could help:

要进一步处理地图数组,以下内容可能会有所帮助:

@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {

  List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
  maps.addAll(payload);

}

回答by Mateusz Stefek

To receive arbitrary Json in Spring-Boot, you can simply use Hymanson's JsonNode. The appropriate converter is automatically configured.

要在 Spring-Boot 中接收任意 Json,您可以简单地使用 Hymanson 的JsonNode. 相应的转换器会自动配置。

    @PostMapping(value="/process")
    public void process(@RequestBody com.fasterxml.Hymanson.databind.JsonNode payload) {
        System.out.println(payload);
    }