文档章节

Spring Boot—08Jackson处理JSON

o
 osc_mervd488
发布于 2018/04/23 18:50
字数 848
阅读 12
收藏 0

精选30+云产品,助力企业轻松上云!>>>



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

}













o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。

暂无文章

Eclipse_JavaEE_Tomcat_MySQL环境配置

安装java环境,配置系统变量(JAVA_HOME,绝对路径) 下载eclipse+Tomcat+mysql window——》preference——》server——》runtime——》tomcat环境 项目右键build path 配mysql jar ,libra...

愿有时光可回首
18分钟前
20
0
MySQL原理 - InnoDB引擎 - 行记录存储 - Redundant行格式

本文基于 MySQL 8 在上一篇:MySQL原理 - InnoDB引擎 - 行记录存储 - Compact格式 中,我们介绍了什么是 InnoDB 行记录存储以及 Compact 行格式,在这一篇中,我们继续介绍其他三种行格式。 ...

zhxhash
39分钟前
17
0
leetcode面试题 17.13(恢复空格)--Java语言实现

求: 哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"I reset the computer. It still didn’t boot!"已经变成了"iresetthecomputeritstilldidntboo...

拓拔北海
47分钟前
19
0
B站跨年晚会究竟做对了什么?

燃财经(ID:rancaijing)原创 作者 | 赵磊 编辑 | 周昶帆 “补课”是《bilibili晚会 二零一九最美的夜》这个视频中,观众在前两分钟刷得最多的弹幕,寓意着观众是在元旦之后回来补看跨年晚会...

子乾建建_Jeff
01/07
45
0
关于Scrapy爬虫项目运行和调试的小技巧(上篇)

点击上方“Python爬虫与数据挖掘”,进行关注 回复“书籍”即可获赠Python从入门到进阶共10本电子书 今 日 鸡 汤 迟日江山丽,春风花草香。泥融飞燕子,沙暖睡鸳鸯。 扫除运行Scrapy爬虫程序...

yuhan336
04/02
26
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部