GVKun编程网logo

尝试使用Spring Boot REST从POST读取JSON字符串(springboot 读取json文件并解析)

8

想了解尝试使用SpringBootREST从POST读取JSON字符串的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于springboot读取json文件并解析的相关问题,此外,我们还将为您

想了解尝试使用Spring Boot REST从POST读取JSON字符串的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于springboot 读取json文件并解析的相关问题,此外,我们还将为您介绍关于JSR-使用Spring Boot对Spring @RestController进行349 bean验证、spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...、spring boot get和post请求,以及requestbody为json串时候的处理、spring boot 返回json字符串 null值转空字符串的新知识。

本文目录一览:

尝试使用Spring Boot REST从POST读取JSON字符串(springboot 读取json文件并解析)

尝试使用Spring Boot REST从POST读取JSON字符串(springboot 读取json文件并解析)

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

这是我的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>

这是我的网络服务代码:

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);    }}

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

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

我收到此错误消息:

{"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.jackson.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"

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

我可能做错了什么?

感谢您抽出时间来阅读…

答案1

小编典典

我认为使用JSON的最简单/便捷的方法是使用类似于JSON的Java类:http://codingdict.com/questions/6613
但是,如果您不能使用Java类,则可以使用这两种解决方案之一。

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

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

使用您的请求:

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

解决方案2: 否则,您可以通过 以下 方式获取POST负载String

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

然后根据需要解析该字符串。请注意,必须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

JSR-使用Spring Boot对Spring @RestController进行349 bean验证

JSR-使用Spring Boot对Spring @RestController进行349 bean验证

我正在使用Spring Boot
1.5.2.RELEASE,并且无法为@RequestParam@PathVariableat方法本身合并JSR-349(bean验证1.1)。

对于POST请求,如果方法参数是Java
POJO,则使用对该参数进行注释@Valid可以正常工作,但使用@RequestParam@PathVariable进行注释@NotEmpty,则@Email不能正常工作。

我已经用Spring注释了控制器类 @Validated

Spring Boot包括- validation-api-1.1.0.Final.jarhibernate- validator-5.3.4.Final.jar

我有什么想念的吗?

示例代码

@RequestMapping(method = RequestMethod.GET,value = "/testValidated",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseBean<String> testValidated(@Email @NotEmpty @RequestParam("email") String email) {
    ResponseBean<String> response = new ResponseBean<>();
    response.setResponse(Constants.SUCCESS);
    response.setMessage("testValidated");
    logger.error("Validator Not called");
    return response; 
}

当我发送空值或格式不正确的电子邮件地址时,永远不会调用下面的处理程序,并且email控制权始终与in testValidated方法一起使用。

@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean handle(ConstraintViolationException exception) {

    StringBuilder messages = new StringBuilder();
    ResponseBean response = new ResponseBean();

    exception.getConstraintViolations().forEach(entry -> messages.append(entry.getMessage() + "\n"));

    response.setResponse(Constants.FAILURE);
    response.setErrorcode(Constants.ERROR_CODE_BAD_REQUEST);
    response.setMessage(messages.toString());
    return response;
}

ResponseBean<T> 是我的应用程序特定的类。

spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...

spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...

spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法 ,这里一共有两种不同解析方式(Jackson 和 FastJson 两种方式,springboot 我用的 1.x 的版本)

第一种方式:默认的 json 处理是 jackson 也就是对 configureMessageConverters 没做配置时

  mybatis 数据查询返回的时间,是一串数字,如何转化成时间。两种方法,推荐第一种

  方法一:

  可以在 apllication.property 加入下面配置就可以

  # 时间戳统一转换
  spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

  spring.jackson.time-zone=GMT+8

 

  方法二:

  @JsonFormat(timezone = "GMT+8", pattern = "yyyyMMddHHmmss")

  private Date createTime;

 

第二种方式:当 configureMessageConverters 配置为 FasJson 处理时;

  方法一:全局配置:    fastJsonConfig.setDateFormat ("yyyy-MM-dd HH:mm:ss");

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );

       //此处是全局处理方式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        fastConverter.setFastJsonConfig(fastJsonConfig);

        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.ALL); // 全部格式
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(fastConverter);
    }    
}

  

  方法二:在所需要的字段上配置(比较灵活的方式,根据不同需求转换):

  @JSONField(format="yyyyMMdd")

  private Date createTime;

说明:这里如果字段和全局都配置了 ,最后是以全局转换

 

重要补充:

当 springboot 版本是 2.0.9 以上配置 fastjson 不生效解决如下:

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 创建配置类
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );

        //此处是全局处理方式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setCharset(Charset.forName("UTF-8"));
        fastConverter.setFastJsonConfig(config);

        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.ALL);
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        //支持text 转string
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
        return new HttpMessageConverters(fastConverter, stringHttpMessageConverter);
    }

 

 参考 spring 官网文档:https://docs.spring.io/spring-boot/docs/2.0.9.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-spring-mvc-message-converters

spring boot get和post请求,以及requestbody为json串时候的处理

spring boot get和post请求,以及requestbody为json串时候的处理

GET、POST方式提时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
  •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
  •     其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);
代码:
 
[java] view plain copy
  1. package com.example.controller;  
  2.   
  3. import org.springframework.web.bind.annotation.GetMapping;  
  4. import org.springframework.web.bind.annotation.PathVariable;  
  5. import org.springframework.web.bind.annotation.RequestBody;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8. import org.springframework.web.bind.annotation.RequestParam;  
  9. import org.springframework.web.bind.annotation.RestController;  
  10.   
  11. import com.example.bean.RequestLoginBean;  
  12. import com.example.response.BaseResponse;  
  13. import com.google.gson.Gson;  
  14.   
  15. @RestController  
  16. @RequestMapping(value = "/index")  
  17. public class Login {  
  18.   
  19.     /** 
  20.      * index home 
  21.      *  
  22.      * @return 
  23.      */  
  24.     @RequestMapping(value = "/home")  
  25.     public String home() {  
  26.         return "index home";  
  27.     }  
  28.       
  29.     /** 
  30.      * 得到1个参数 
  31.      *  
  32.      * @param name 
  33.      *            用户名 
  34.      * @return 返回结果 
  35.      */  
  36.     @GetMapping(value = "/{name}")  
  37.     public String index(@PathVariable String name) {  
  38.         return "oh you are " + name + "<br> nice to meet you";// \n不起作用了,那就直接用html中的标签吧  
  39.     }  
  40.   
  41.     /** 
  42.      * 简单post请求 
  43.      *  
  44.      * @param name 
  45.      * @param pwd 
  46.      * @return 
  47.      */  
  48.     @RequestMapping(value = "/testpost", method = RequestMethod.POST)  
  49.     public String testpost() {  
  50.         System.out.println("hello  test post");  
  51.         return "ok";  
  52.     }  
  53.   
  54.     /** 
  55.      * 同时得到两个参数 
  56.      *  
  57.      * @param name 
  58.      *            用户名 
  59.      * @param pwd 
  60.      *            密码 
  61.      * @return 返回结果 
  62.      */  
  63.     @GetMapping(value = "/login/{name}&{pwd}")  
  64.     public String login(@PathVariable String name, @PathVariable String pwd) {  
  65.         if (name.equals("admin") && pwd.equals("admin")) {  
  66.             return "hello welcome admin";  
  67.         } else {  
  68.             return "oh sorry user name or password is wrong";  
  69.         }  
  70.     }  
  71.   
  72.     /** 
  73.      * 通过get请求去登陆 
  74.      *  
  75.      * @param name 
  76.      * @param pwd 
  77.      * @return 
  78.      */  
  79.     @RequestMapping(value = "/loginbyget", method = RequestMethod.GET)  
  80.     public String loginByGet(@RequestParam(value = "name", required = true) String name,  
  81.             @RequestParam(value = "pwd", required = true) String pwd) {  
  82.         return login4Return(name, pwd);  
  83.     }  
  84.   
  85.     /** 
  86.      * 通过post请求去登陆 
  87.      *  
  88.      * @param name 
  89.      * @param pwd 
  90.      * @return 
  91.      */  
  92.     @RequestMapping(value = "/loginbypost", method = RequestMethod.POST)  
  93.     public String loginByPost(@RequestParam(value = "name", required = true) String name,  
  94.             @RequestParam(value = "pwd", required = true) String pwd) {  
  95.         System.out.println("hello post");  
  96.         return login4Return(name, pwd);  
  97.     }  
  98.   
  99.     /** 
  100.      * 参数为一个bean对象.spring会自动为我们关联映射 
  101.      * @param loginBean 
  102.      * @return 
  103.      */  
  104.     @RequestMapping(value = "/loginbypost1", method = { RequestMethod.POST, RequestMethod.GET })  
  105.     public String loginByPost1(RequestLoginBean loginBean) {  
  106.         if (null != loginBean) {  
  107.             return login4Return(loginBean.getName(), loginBean.getPwd());  
  108.         } else {  
  109.             return "error";  
  110.         }  
  111.     }  
  112.       
  113.     /** 
  114.      * 请求内容是一个json串,spring会自动把他和我们的参数bean对应起来,不过要加@RequestBody注解 
  115.      *  
  116.      * @param name 
  117.      * @param pwd 
  118.      * @return 
  119.      */  
  120.     @RequestMapping(value = "/loginbypost2", method = { RequestMethod.POST, RequestMethod.GET })  
  121.     public String loginByPost2(@RequestBody RequestLoginBean loginBean) {  
  122.         if (null != loginBean) {  
  123.             return login4Return(loginBean.getName(), loginBean.getPwd());  
  124.         } else {  
  125.             return "error";  
  126.         }  
  127.     }  
  128.   
  129.       
  130.   
  131.   
  132.     /** 
  133.      * 对登录做出响应处理的方法 
  134.      *  
  135.      * @param name 
  136.      *            用户名 
  137.      * @param pwd 
  138.      *            密码 
  139.      * @return 返回处理结果 
  140.      */  
  141.     private String login4Return(String name, String pwd) {  
  142.         String result;  
  143.         BaseResponse response = new BaseResponse();  
  144.         if (name.equals("admin") && pwd.equals("admin")) {  
  145.             result = "hello welcome admin";  
  146.             response.setState(true);  
  147.         } else {  
  148.             result = "oh sorry user name or password is wrong";  
  149.             response.setState(false);  
  150.         }  
  151.         System.out.println("收到请求,请求结果:" + result);  
  152.         return new Gson().toJson(response);  
  153.     }  
  154. }  


spring boot 返回json字符串 null值转空字符串

spring boot 返回json字符串 null值转空字符串

@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

关于尝试使用Spring Boot REST从POST读取JSON字符串springboot 读取json文件并解析的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于JSR-使用Spring Boot对Spring @RestController进行349 bean验证、spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...、spring boot get和post请求,以及requestbody为json串时候的处理、spring boot 返回json字符串 null值转空字符串的相关知识,请在本站寻找。

本文标签: