

接收前端的JSON数据,接收.net接口的JSON数据,遇到IsOpen,IsValid,解析不出来!遇到鬼似的~~一个小实验,找到出路!
实验数据准备
直接在浏览器的console里,输入
JSON.stringify({IsOpen:true,IsValid:false})//得到实验串
//大概放到变量里是这样//String json = "[{\"IsOpen\":true,\"IsValid\":false},{\"IsOpen\":true,\"IsValid\":true}]";String json = "{\"IsOpen\":true,\"IsValid\":true}";
准备简单工程
建一个纯净的java工程,快速调试,不然时间都浪费在编译上了。
main方法
public class BootMe {@SuppressWarnings("unused")public static void main(String[] args) throws InterruptedException, IOException {//String json = "[{\"IsOpen\":true,\"IsValid\":false},{\"IsOpen\":true,\"IsValid\":true}]";String json = "{\"IsOpen\":true,\"IsValid\":true}";JsonBean result = (JsonBean) JSON.parseObject(json, JsonBean.class);JsonBean result1 = new ObjectMapper().readValue(json, JsonBean.class);System.out.println(json);System.out.println("==after==");System.out.println(JSON.toJSONString(result));System.out.println(new ObjectMapper().writeValueAsString(result));System.out.println(new ObjectMapper().writeValueAsString(result1));System.out.println("==end==");}}
Bean
package cn.test;import com.fasterxml.jackson.annotation.JsonProperty;import lombok.Data;public class JsonBean {private boolean open;private boolean valid;public void setIsValid(boolean valid) {this.valid = valid;}}
实验结果
{"IsOpen":true,"IsValid":true}==after=={"open":false,"valid":false}{"IsOpen":false,"IsValid":false}{"IsOpen":true,"IsValid":true}==end==
实验操作组合就不细化了,实验的结论是
一、如果使用JSON.parseObject,或希望controller正常接收到类似isValid的参数值,可以采用以下方式定义Bean
package cn.test;import com.fasterxml.jackson.annotation.JsonProperty;import lombok.Data;public class JsonBean {private boolean valid;}public void setIsValid(boolean valid) {this.valid = valid;}
二、使用希望使用@JsonProperty(“IsValid”),来解决此问题,请使用ObjectMapper。
本实验所用到的POM包
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.4</version></dependency><!-- json --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.7.3</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.7.3</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.7.3</version></dependency>
感受
java的boolean设计,有点过度设计了,设计者以自身的想法为boolean增加了有区于其他类型的特性,然后被无数人踩坑~受不了的人就再立门户,出新语言了!


技术岛公众号