欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

json转换之gson

程序员文章站 2022-06-15 13:49:47
...

工具类,有待以后复用

jar包依赖

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
	<dependency>
	    <groupId>com.google.code.gson</groupId>
	    <artifactId>gson</artifactId>
	    <version>2.8.2</version>
	</dependency>
package info.lumanman.GsonUtil;

import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

public class GsonUtil {

	private final static Gson gson=new Gson();
    private GsonUtil() {

    }
    public static Gson getInstance(){
        return gson;
    }
    /**
     * javaBean、列表、数组、转换为json字符串
     */
    public static String obj2json(Object obj) throws Exception {
        return gson.toJson(obj, Object.class);
    }

    /**
     *  json 转JavaBean、Map
     */

    public static <T> T json2pojo(String jsonString,Class<T> clazz) throws Exception {

        return gson.fromJson(jsonString,clazz);
    }



	/**
     *  json字符串转换为同类型的value-->map
     */
    public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) throws Exception {
    	Type type = new TypeToken<Map<String,LinkedTreeMap<String, T>>>() {}.getType();
    	Map<String,LinkedTreeMap<String, T>> map=gson.fromJson(jsonString, type);
        Map<String,T> result=new HashMap<String, T>();
        for(Map.Entry<String,LinkedTreeMap<String, T>> entry:map.entrySet()){
            result.put(entry.getKey(),json2pojo(obj2json(entry.getValue()), clazz));
        }
        return result;
    }

    /**
     *  与javaBean json数组字符串转换为列表
     */
    public static <T> List<T> json2list(String jsonString,Class<T> clazz) throws Exception {
        Type type = new TypeToken<ArrayList<LinkedTreeMap<String, T>>>() {}.getType();
        ArrayList<LinkedTreeMap<String, T>> sList=gson.fromJson(jsonString, type);
        List<T> result=new ArrayList<T>();
        for(LinkedTreeMap<String, T> map:sList){
            result.add(json2pojo(obj2json(map), clazz));
        }
        return result;

    }


    /**
     * json 转List<LinkedHashMap<String,Object>>
     * @param map
     * @return
     */
    public static List<LinkedTreeMap<String,Object>> json2listMap(String json) {

        List<LinkedTreeMap<String,Object>> list = new ArrayList<LinkedTreeMap<String,Object>>();
        list =   gson.fromJson(json, List.class);

        return list;
    }
    
    /**
     * json文件 转pojo
     * 注意这里的file文件最好是新建的notepadd++,并保存为UTF-8的文件,防止乱码
     * @param map
     * @return
     */
    public static <T> T file2pojo(FileReader fileReader ,Class<T> clazz) {
          return gson.fromJson(fileReader, clazz);

    }
}
package info.lumanman.GsonUtil;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.google.gson.internal.LinkedTreeMap;

import info.lumanman.JacksonUtil.JacksonUtil;
import info.lumanman.JacksonUtil.School;
import info.lumanman.JacksonUtil.Student;

public class GsonTest {

	/**
     * javaBean、列表、数组、Map转换为json字符串
     */
	@Test
	public void obj2jsonTest() throws Exception {
		School school=new School();
		school.setAddress("安徽");
		school.setName("圣泉中学");
		
		Student student=new Student();
		student.setAge(18);
		student.setName("张三");
		
		Student student2=new Student();
		student2.setAge(18);
		student2.setName("张三");
		
		List<Student> list=new ArrayList<Student>();
		list.add(student);
		list.add(student2);
		school.setStudentList(list);
		
		String json=GsonUtil.obj2json(school);
		System.out.println(json);
	}
	
	/**
     *  json 转JavaBean、Map
     */
	@Test
	public void json2pojoTest() throws Exception {
		String jsonString="{\"a\": 0,"+
							"\"name\": \"圣泉中学\","+
							"\"address\": \"安徽\","+
							"\"createdDate\": null,"+
							"\"studentList\": [{"+
								"\"name\": \"张三\","+
								"\"age\": 18"+
							"},"+
							"{"+
								"\"name\": \"张三\","+
								"\"age\": 18}]}";
		
		Map<String, Object> map=GsonUtil.json2pojo(jsonString,Map.class);
		System.out.println(map);
	}
	
	/**
     *  json字符串转换为map
     */
	@Test
	public void json2mapClassTest() throws Exception {
		String jsonString="{\"student\": {"+
					"\"name\": \"张三\","+
					"\"age\": 18}}";
		
		Map<String, Student> map=GsonUtil.json2map(jsonString,Student.class);
		System.out.println(map.get("student").getAge());
	}
	
	/**
     *  与javaBean json数组字符串转换为列表
     */
	@Test
	public void json2listTest() throws Exception {
		String jsonString="[{\"name\": \"张三\","+
					"\"age\": 18"+
				"},"+
				"{"+
					"\"name\": \"张三\","+
					"\"age\": 18}]";
		
		List<Student> studentList=GsonUtil.json2list(jsonString,Student.class);
		System.out.println(studentList.get(0).getAge());
	}
	
	/**
     * json 转List<LinkedHashMap<String,Object>>
     * @param map
     * @return
     */
	@Test
	public void json2listMapTest() throws Exception {
		String jsonString="[{"+
					"\"name\": \"张三\","+
					"\"age\": 18"+
				"},"+
				"{"+
					"\"name\": \"张三\","+
					"\"age\": 18}]";
		
		List<LinkedTreeMap<String, Object>> list=GsonUtil.json2listMap(jsonString);
		System.out.println(list.get(0).get("name"));
	}
	
	/**
     * json文件 转pojo
     * 注意这里的file文件最好是新建的notepadd++,并保存为UTF-8的文件,防止乱码
     * @param map
     * @return
     */
	@Test
	public void file2pojoTest() throws Exception {
		File file=new File("C:\\Users\\WM\\Desktop\\utf-8报文.txt");
		School school=GsonUtil.file2pojo(new FileReader(file),School.class);
		System.out.println(school);
	}
	
}
package info.lumanman.JacksonUtil;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class School implements Serializable{

	private int a;
	private String name;
	
	private String address;
	
	private Date createdDate;
	
	private List<Student> studentList;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public List<Student> getStudentList() {
		return studentList;
	}

	public void setStudentList(List<Student> studentList) {
		this.studentList = studentList;
	}

	public Date getCreatedDate() {
		return createdDate;
	}

	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	@Override
	public String toString() {
		return "School [a=" + a + ", name=" + name + ", address=" + address + ", createdDate=" + createdDate
				+ ", studentList=" + studentList + "]";
	}
	
	
}
package info.lumanman.JacksonUtil;

public class Student {

	private String name;
	
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
	
}

UTF-8文件内容

{
	"a": 0,
	"name": "圣泉中学",
	"address": "安徽",
	"createdDate": null,
	"studentList": [{
		"name": "张三",
		"age": 18
	},
	{
		"name": "张三",
		"age": 18
	}]
}