想了解尝试使用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文件并解析)
- 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通过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验证
我正在使用Spring Boot
1.5.2.RELEASE,并且无法为@RequestParam
&@PathVariable
at方法本身合并JSR-349(bean验证1.1)。
对于POST请求,如果方法参数是Java
POJO,则使用对该参数进行注释@Valid
可以正常工作,但使用@RequestParam
&@PathVariable
进行注释@NotEmpty
,则@Email
不能正常工作。
我已经用Spring注释了控制器类 @Validated
Spring Boot包括- validation-api-1.1.0.Final.jar
和hibernate-
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 我用的 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串时候的处理
GET、POST方式提时, 根据request header Content-Type的值来判断:
- application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
- multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
- 其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);
- package com.example.controller;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- 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.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
- import com.example.bean.RequestLoginBean;
- import com.example.response.BaseResponse;
- import com.google.gson.Gson;
- @RestController
- @RequestMapping(value = "/index")
- public class Login {
- /**
- * index home
- *
- * @return
- */
- @RequestMapping(value = "/home")
- public String home() {
- return "index home";
- }
- /**
- * 得到1个参数
- *
- * @param name
- * 用户名
- * @return 返回结果
- */
- @GetMapping(value = "/{name}")
- public String index(@PathVariable String name) {
- return "oh you are " + name + "<br> nice to meet you";// \n不起作用了,那就直接用html中的标签吧
- }
- /**
- * 简单post请求
- *
- * @param name
- * @param pwd
- * @return
- */
- @RequestMapping(value = "/testpost", method = RequestMethod.POST)
- public String testpost() {
- System.out.println("hello test post");
- return "ok";
- }
- /**
- * 同时得到两个参数
- *
- * @param name
- * 用户名
- * @param pwd
- * 密码
- * @return 返回结果
- */
- @GetMapping(value = "/login/{name}&{pwd}")
- public String login(@PathVariable String name, @PathVariable String pwd) {
- if (name.equals("admin") && pwd.equals("admin")) {
- return "hello welcome admin";
- } else {
- return "oh sorry user name or password is wrong";
- }
- }
- /**
- * 通过get请求去登陆
- *
- * @param name
- * @param pwd
- * @return
- */
- @RequestMapping(value = "/loginbyget", method = RequestMethod.GET)
- public String loginByGet(@RequestParam(value = "name", required = true) String name,
- @RequestParam(value = "pwd", required = true) String pwd) {
- return login4Return(name, pwd);
- }
- /**
- * 通过post请求去登陆
- *
- * @param name
- * @param pwd
- * @return
- */
- @RequestMapping(value = "/loginbypost", method = RequestMethod.POST)
- public String loginByPost(@RequestParam(value = "name", required = true) String name,
- @RequestParam(value = "pwd", required = true) String pwd) {
- System.out.println("hello post");
- return login4Return(name, pwd);
- }
- /**
- * 参数为一个bean对象.spring会自动为我们关联映射
- * @param loginBean
- * @return
- */
- @RequestMapping(value = "/loginbypost1", method = { RequestMethod.POST, RequestMethod.GET })
- public String loginByPost1(RequestLoginBean loginBean) {
- if (null != loginBean) {
- return login4Return(loginBean.getName(), loginBean.getPwd());
- } else {
- return "error";
- }
- }
- /**
- * 请求内容是一个json串,spring会自动把他和我们的参数bean对应起来,不过要加@RequestBody注解
- *
- * @param name
- * @param pwd
- * @return
- */
- @RequestMapping(value = "/loginbypost2", method = { RequestMethod.POST, RequestMethod.GET })
- public String loginByPost2(@RequestBody RequestLoginBean loginBean) {
- if (null != loginBean) {
- return login4Return(loginBean.getName(), loginBean.getPwd());
- } else {
- return "error";
- }
- }
- /**
- * 对登录做出响应处理的方法
- *
- * @param name
- * 用户名
- * @param pwd
- * 密码
- * @return 返回处理结果
- */
- private String login4Return(String name, String pwd) {
- String result;
- BaseResponse response = new BaseResponse();
- if (name.equals("admin") && pwd.equals("admin")) {
- result = "hello welcome admin";
- response.setState(true);
- } else {
- result = "oh sorry user name or password is wrong";
- response.setState(false);
- }
- System.out.println("收到请求,请求结果:" + result);
- return new Gson().toJson(response);
- }
- }
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值转空字符串的相关知识,请在本站寻找。
本文标签: