• jackson序列化和反序列化Json


    jackson包提供了java对象与json相互转换的API。

    jackson转换机制

    Jackson要求java对象是一个POJO对象,即它是一个普通JavaBean对象。此外,如果字段是用private修饰的,则必须有getXXX()方法,否则字段用public修饰。

    json常见格式如下

    {
        "key1" : value,
        "key2" : [...],
        "key3" : {...}
    }
    

    jackson把JavaBean对象的每个字段映射为json的键,json键值由JavaBean的getXXX()方法确定。

    json键值从形式上看,可以分为基本类型(字符串、数值)、数组、字典。当JavaBean的字段声明为基本类型时对应json的基本类型,当JavaBean声明为数组或链表时对应json的数组类型,当JavaBean声明为字典或对象时对应json的字典类型。

    序列化

    定义一个符合JavaBean规则的类

    package com.weixia.Json;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Bean {
    	private String name;
    	
    	private int[] stature;
    	
    	private Friend friend;
    	
    	private ArrayList<String> song;
    	
    	private Map<String,Integer> score = new HashMap<String,Integer>();
    	
    	public Bean(String name) {
    		this.name = name;
    	}
    	
    	public String getName() {
    		return this.name;
    	}
    	
    	public void setStature(int[] stature) {
    		this.stature = stature;
    	}
    	
    	public int[] getStature() {
    		return this.stature;
    	}
    	
    	public void setSong(ArrayList<String> song) {
    		this.song = song;
    	}
    	
    	public ArrayList<String> getSong() {
    		return this.song;
    	}
    	
    	public void setFriend(Friend friend) {
    		this.friend = friend;
    	}
    	
    	public Friend getFriend() {
    		return this.friend;
    	}
    	
    	public void addScore(String subject,Integer score) {
    		this.score.put(subject, score);
    	}
    	
    	public Map getScore() {
    		return this.score;
    	}
    }
    
    
    class Friend {
    	public String name;
    	public int age;
    }
    

    将Bean对象序列化为json如下

    
    package com.weixia.Json;
    
    import java.util.ArrayList;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    
    public class App 
    {
        public static void main( String[] args ) throws Exception
        {
            Bean bean = new Bean("Album");
        	ObjectMapper mapper = new ObjectMapper();
        	
        	bean.setStature(new int[] {88,60,89});
        	
        	ArrayList<String> song = new ArrayList<String>();
        	song.add("奇异恩典");
        	song.add("东京的都");
        	bean.setSong(song);
        	
        	Friend friend = new Friend();
        	friend.name = "小明";
        	friend.age = 24;
        	bean.setFriend(friend);
        	
        	bean.addScore("Math", 100);
        	bean.addScore("PE", 88);
        	
            mapper.configure(SerializationFeature.INDENT_OUTPUT, true);	//格式化输出
            mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);	//键按自然顺序输出
            mapper.setSerializationInclusion(Include.NON_EMPTY);	//忽略POJO中属性为空的字段
            mapper.writeValue(System.out, bean);
        }
    }
    

    反序列化

    json文件如下:

    {
        "name": "weixia",
        "age": 24,
        "stature":[89,66,89],
        "friend":{
            "name":"zhiye",
            "age":24
        },
        "test":""
    }
    

    定义一个符合JaveBean规则的类

    package com.weixia.Json;
    
    public class People {
    	private String name;
    	private int age;
    	private Friend friend;
    	private int[] stature;
    	public String getName() {
    		return this.name;
    	}
    	
    	public int getAge() {
    		return this.age;
    	}
    	
    	public Friend getFriend() {
    		return this.friend;
    	}
    	
    	public int[] getStature() {
    		return this.stature;
    	}
    }
    
    
    class Friend {
    	public String name;
    	public int age;
    }
    

    将json反序列化为java对象

    package com.weixia.Json;
    
    import java.io.File;
    
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class Json2Bean {
    
    	public static void main(String[] args) throws Exception {
    		ObjectMapper mapper = new ObjectMapper();
    		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //忽略未知的属性
    		People people = mapper.readValue(new File("F:\test.json"), People.class);
    		
    		System.out.println(people.getName());
    		System.out.println(people.getAge());
    		System.out.println(people.getFriend());
    		int[] stature = people.getStature();
    		for (int num : stature) {
    			System.out.println(num);
    		}
    	}
    
    }
    
  • 相关阅读:
    【系列】CentOS 7.3 离线安装(无网络环境)CI CD环境之sonarqube配置
    Abp vnext 配置Swagger增加token认证
    sonarqube+gitlab runner +docker 代码质量检查问题汇总
    【EF Core】EF core中使用FluentAPI对外键进行指定配置
    【系列】CentOS 7.3 离线安装(无网络环境)CI CD环境之gitlab runner 关于私有docker仓库配置
    【系列】CentOS 7.3 离线安装(无网络环境)CI CD环境之harbor
    【系列】CentOS 7.3 离线安装(无网络环境)CI CD环境之gitlab + gitlab runner(docker in docker)
    【杂记】关于在实际项目中使用TDD的方法
    【系列】CentOS 7.3 离线安装(无网络环境)CI CD环境之docker+docker compose
    【TeamCity】使用TeamCity搭建ASP.NET Core + SVN 的 CICD环境
  • 原文地址:https://www.cnblogs.com/weixia-blog/p/9665189.html
Copyright © 2020-2023  润新知