Spring Boot—08Jackson处理JSON
package com.sample.smartmap.controller; import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.bee.sample.ch3.entity.User;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider; @Controller
@RequestMapping("/jackson")
public class JacksonSampleController { Log log = LogFactory.getLog(JacksonSampleController.class);
//参考JacksonConf
@Autowired ObjectMapper mapper; @GetMapping("/now.json")
public @ResponseBody Map now(){
Map map = new HashMap();
map.put("date", new Date());
return map;
}
// 以类似于XML DOM的方式进行解析JSON格式的数据
@GetMapping("/readtree.json")
public @ResponseBody String readtree() throws JsonProcessingException, IOException{
String json = "{\"name\":\"lijz\",\"id\":10}";
JsonNode node = mapper.readTree(json); String name = node.get("name").asText();
int id = node.get("id").asInt();
return "name:"+name+",id:"+id; } // 以对象绑定的方式解析JSON数据
@GetMapping("/databind.json")
public @ResponseBody String databind() throws JsonProcessingException, IOException{
String json = "{\"name\":\"lijz\",\"id\":10}";
User user = mapper.readValue(json, User.class);
return "name:"+user.getName()+",id:"+user.getId(); } // 将对象转化为JSON字符串
@GetMapping("/serialization.json")
public @ResponseBody String custom() throws JsonProcessingException { User user = new User();
user.setId(1l);
user.setName("hello");
String str = mapper.writeValueAsString(user); return str; } @JsonIgnoreProperties ({"id","photo"})
public static class SamplePojo{
Long id;
String name;
byte[] photo;
@JsonIgnore
BigDecimal salary;
Map<String , Object> otherProperties = new HashMap<String , Object>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
@JsonAnyGetter
public Map<String, Object> getOtherProperties() {
return otherProperties;
}
@JsonAnySetter
public void setOtherProperties(Map<String, Object> otherProperties) {
this.otherProperties = otherProperties;
} } // 以Token的方式生成Java对象
public static class Usererializer extends JsonSerializer<User> {
@Override
public void serialize(User value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("user-name", value.getName());
jgen.writeEndObject();
}
}
// 以XML DOM的方式生成Java对象
public class UserDeserializer extends JsonDeserializer<User> { @Override
public User deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
String name = node.get("user-name").asText();
User user = new User();
user.setName(name);
return user;
}
} }
package com.smartmap.sample.conf; import java.text.SimpleDateFormat; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
public class JacksonConf { @Bean
@Primary
public ObjectMapper getObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return objectMapper;
}
}
package com.smartmap.sample.entity; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView; public class User {
public interface IdView {};
public interface IdNameView extends IdView {}; @JsonView(IdView.class)
private Integer id;
@JsonView(IdNameView.class)
private String name;
@JsonIgnore
BigDecimal salary; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public BigDecimal getSalary() {
return salary;
} public void setSalary(BigDecimal salary) {
this.salary = salary;
} }
package com.smartmap.sample.controller; import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.smartmap.sample.entity.User;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper; @Controller
public class DataBindController {
@Autowired
ObjectMapper mapper; @RequestMapping("/updateUsers.json")
public @ResponseBody String say(@RequestBody List<User> list) {
StringBuilder sb = new StringBuilder();
for (User user : list) {
sb.append(user.getName()).append(" ");
}
return sb.toString();
} @RequestMapping("/customize.json")
public @ResponseBody String customize() throws JsonParseException, JsonMappingException, IOException {
String jsonInput = "[{\"id\":2,\"name\":\"xiandafu\"},{\"id\":3,\"name\":\"lucy\"}]";
JavaType type = getCollectionType(List.class,User.class);
List<User> list = mapper.readValue(jsonInput, type);
return String.valueOf(list.size());
}
//产生一个集合类型说明
public JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
// User的ID字段不转化为JSON
@JsonView(User.IdView.class)
@RequestMapping("/id.json")
public @ResponseBody User queryIds() {
User user = new User();
user.setId(1);
user.setName("hell");
return user;
} @RequestMapping("/dept.json")
public @ResponseBody Department getDepartment() {
return new Department(1);
} class Department {
Map map = new HashMap();
int id ;
public Department(int id){
this.id = id;
map.put("newAttr", 1);
}
// 将其它任何不配的键值都放入map中
@JsonAnyGetter
public Map<String, Object> getOtherProperties() {
return map;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} } }
package com.smartmap.sample.controller; import java.io.IOException;
import java.io.StringWriter; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.smartmap.sample.entity.User;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper; @Controller
@RequestMapping("/stream")
public class JacksonStreamController {
Log log = LogFactory.getLog(JacksonStreamController.class);
@Autowired
ObjectMapper mapper;
// 以Token的方式解析JSON字符串
@RequestMapping("/parser.html")
public @ResponseBody String parser() throws JsonParseException, IOException{
String json = "{\"name\":\"lijz\",\"id\":10}";
JsonFactory f = mapper.getFactory();
String key=null,value=null;
JsonParser parser = f.createParser(json);
// {
JsonToken token = parser.nextToken();
//"name"
token = parser.nextToken();
if(token==JsonToken.FIELD_NAME){
key = parser.getCurrentName(); } token = parser.nextToken();
//"lijz"
value = parser.getValueAsString();
parser.close();
return key+","+value; } // 以Token的方式生成JSON字符串
@RequestMapping("/generator.html")
public @ResponseBody String generator() throws JsonParseException, IOException{
JsonFactory f = mapper.getFactory();
//输出到stringWriter
StringWriter sw = new StringWriter();
JsonGenerator g = f.createGenerator(sw);
// {
g.writeStartObject(); // "message", "Hello world!"
g.writeStringField("name", "lijiazhi");
// }
g.writeEndObject();
g.close();
return sw.toString();
} }
Spring Boot—08Jackson处理JSON的更多相关文章
- spring boot @ResponseBody转换JSON 时 Date 类型处理方法,Jackson和FastJson两种方式,springboot 2.0.9配置fastjson不生效官方解决办法
spring boot @ResponseBody转换JSON 时 Date 类型处理方法 ,这里一共有两种不同解析方式(Jackson和FastJson两种方式,springboot我用的1.x的版 ...
- Spring Boot 之使用 Json 详解
Spring Boot 之使用 Json 详解 简介 Spring Boot 支持的 Json 库 Spring Web 中的序列化.反序列化 指定类的 Json 序列化.反序列化 @JsonTest ...
- Spring Boot Security And JSON Web Token
Spring Boot Security And JSON Web Token 说明 流程说明 何时生成和使用jwt,其实我们主要是token更有意义并携带一些信息 https://github.co ...
- Spring boot之返回json数据
1.步骤: 1. 编写实体类Demo 2. 编写getDemo()方法 3. 测试 2.项目构建 编写实体类Demo package com.kfit; /** * 这是一个测试实体类. */ pub ...
- Spring Boot 之遇见JSON
MVC框架中,Spring Boot内置了jackson来完成JSON的序列化和反序列化操作,并且,在与其他技术集成的时候,如Redis.MongoDB.Elasticsearch等对象序列化,都可使 ...
- Spring Boot HTTP over JSON 的错误码异常处理
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “年轻人不要怕表现,要敢于出来表现,但还是那句话,要有正确的度,你的表现是分析问题和解决问题的能 ...
- Spring Boot默认的JSON解析框架设置
方案一:启动类继承WebMvcConfigurerAdapter,覆盖方法configureMessageConverters ... @SpringBootApplication public cl ...
- Spring boot中自定义Json参数解析器
转载请注明出处... 一.介绍 用过springMVC/spring boot的都清楚,在controller层接受参数,常用的都是两种接受方式,如下 /** * 请求路径 http://127.0. ...
- (4)Spring Boot使用别的json解析框架【从零开始学Spring Boot】
此文章已经废弃,请看新版的博客的完美解决方案: 78. Spring Boot完美使用FastJson解析JSON数据[从零开始学Spring Boot] http://412887952-qq-co ...
随机推荐
- 【HDU5126】 stars k-d树
题目大意:有$m$个操作,分两种:在指定三维坐标内加入一个点,询问指定空间内点的数量. 其中$m≤5*10^{4},1≤x,y,z≤10^9$ 这题几乎就是裸的$k-d$树啊.我们动态维护一棵$k-d ...
- HTTP请求头及其作用 转
HTTP请求头Header及其作用详解 下面是访问的一个URL,http://www.hzau.edu.cn的一个header,根据实例分析各部分的功能和作用. 1.Accept,浏览器端能够处理的内 ...
- 使用TopShelf做windows服务
class Program { static void Main(string[] args) { HostFactory.Run(x => { x.RunAsLocalSystem(); x. ...
- Java之集合(十九)LinkedBlockingDeque
转载请注明源出处:http://www.cnblogs.com/lighten/p/7494577.html 1.前言 本章介绍LinkedBlockingDeque,这是一个可选容量的有界双向链表队 ...
- 腾讯云域名申请+ssl证书申请+springboot配置https
阿里云域名申请 域名申请比较简单,使用微信注册阿里云账号并登陆,点击产品,选择域名注册 输入你想注册的域名 进入域名购买页面,搜索可用的后缀及价格,越热门的后缀(.com,.cn)越贵一般,并且很可能 ...
- https数字证书交换过程介绍
文章转自:https://www.2cto.com/kf/201804/739010.html,感谢原作者的辛苦整理,讲解的很清楚,谢谢. [https数字证书交换过程介绍] 注意:该问的背景用到了非 ...
- 《Mysql技术内幕,Innodb存储引擎》——事物
事物 事物中的操作要么都成功要么都不做,这是事物的目的,也是事物模型与文件系统的重要特征之一. 扁平事物(Flat Transactions) 所有操作都处于同一层次,要么都做要么都执行要么都回滚,无 ...
- lua的克隆函数,table的深度拷贝
--深度拷贝Table function DeepCopy(obj) local InTable = {}; local function Func(obj) if type(obj) ~= &quo ...
- Integer.parseInt() 和 valueOf()
parseInt("1")返回的是int类型,所以如果想要将一个String类型的数字串转为原始类型int ,建议使用这个方法, 而不是使用 valueOf("1&quo ...
- rails image_tag生成图片标签
image_tag(source, options={}) Link Returns an HTML image tag for thesource. The source can be a full ...