Gson uses three (collection processing, one-to-many processing)

Please reprint from the source: http://eksliang.iteye.com/blog/2175532

I. Overview

       Map is stored in the form of key-value pairs, and the format of Json is also in the form of key-value pairs, so under normal circumstances, the conversion between map and json should be a matter of course.

2. Map reference example

package com.ickes.json;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ickes.json.daomain.User;
/**
 * Gson's processing of Map
 * @author Ickes
 *
 */
public class MapTest {
	public static void main(String[] args) {
		/**
		 * Ordinary map processing
		 */
		Map<String,String> map = new HashMap<String,String>();
		map.put("name","ickes");
		map.put("pwd", "123");
		Gson gson = new GsonBuilder ()
		.enableComplexMapKeySerialization()
		.setPrettyPrinting()
		.setDateFormat("yyyy-MM-dd HH:mm:ss")
		.create();
		// serialization of map
		String json=gson.toJson(map);
		System.out.println("Serialization of map:\n"+json);
		//Deserialize the map
		Type typeMap = new TypeToken<Map<String,String>>(){}.getType();
		map = gson.fromJson(json,typeMap);
		System.out.println("Deserialization of map:");
		for (Map.Entry<String,String> entry: map.entrySet()) {
			System.out.println(entry.getKey()+"-"+entry.getValue());
		}
		
		/**
		 */map object test
		 */
		Map<String,User> mapUser = new HashMap<String,User>();
		User user1 = new User("A001", "xl","xl_123",24,12000F,new Date());
		User user2 = new User("A002", "x2","xl_223",24,13000F,new Date());
		mapUser.put("user1",user1);
		mapUser.put("user2",user2);
		json = gson.toJson (mapUser);
		System.out.println("Serialization of Map object:\n"+json);
		//Deserialize the map object
		Type typeUser = new TypeToken<Map<String,User>>(){}.getType();
		mapUser = gson.fromJson (json, typeUser);
		System.out.println("Deserialization of map object:");
		for (Map.Entry<String,User> entry: mapUser.entrySet()) {
			System.out.println(entry.getKey()+"-"+entry.getValue());
		}
		
		/**
		 * Integration test
		 */
		Map<String,List<User>> mapList = new HashMap<String,List<User>>();
		List<User> users = new ArrayList<User>();
		users.add(user1);
		users.add(user2);
		mapList.put("mapList",users);
		//Serialization
		json = gson.toJson(mapList);
		System.out.println("Serialization of mapList:\n"+json);
		// deserialize
		Type typeMapList = new TypeToken<Map<String,List<User>>>(){}.getType();
		mapList = gson.fromJson (json, typeMapList);
		System.out.println("Deserialization of mapList object:");
		for (Map.Entry<String,List<User>> entry: mapList.entrySet()) {
			System.out.println(entry.getKey()+"-"+entry.getValue());
		}
	}
}

 Return result:

Serialization of map:
{
  "pwd": "123",
  "name": "ickes"
}
Deserialization of map:
pwd-123
name-ickes
Serialization of Map objects:
{
  "user2": {
    "id": "A002",
    "userName": "x2",
    "userPwd": "xl_223",
    "age": 24,
    "price": 13000.0,
    "birthday": "2015-01-13 16:06:48"
  },
  "user1": {
    "id": "A001",
    "userName": "xl",
    "userPwd": "xl_123",
    "age": 24,
    "price": 12000.0,
    "birthday": "2015-01-13 16:06:48"
  }
}
Deserialization of the map object:
user2-User [id=A002, userName=x2, userPwd=xl_223, age=24, price=13000.0, birthday=Tue Jan 13 16:06:48 CST 2015]
user1-User [id=A001, userName=xl, userPwd=xl_123, age=24, price=12000.0, birthday=Tue Jan 13 16:06:48 CST 2015]
Serialization of mapList:
{
  "mapList": [
    {
      "id": "A001",
      "userName": "xl",
      "userPwd": "xl_123",
      "age": 24,
      "price": 12000.0,
      "birthday": "2015-01-13 16:06:48"
    },
    {
      "id": "A002",
      "userName": "x2",
      "userPwd": "xl_223",
      "age": 24,
      "price": 13000.0,
      "birthday": "2015-01-13 16:06:48"
    }
  ]
}
Deserialization of mapList object:
mapList-[User [id=A001, userName=xl, userPwd=xl_123, age=24, price=12000.0, birthday=Tue Jan 13 16:06:48 CST 2015], User [id=A002, userName=x2, userPwd=xl_223, age=24, price=13000.0, birthday=Tue Jan 13 16:06:48 CST 2015]]

         Tips: When Gson serializes Map, by default, it calls the toString method of Key to get the Key of its JSON string. For simple types and string types, this is no problem, but for complex data objects, if the object does not Override the toString method, then the default toString method will get the Hash address of this object, and enable serialization of the Map key (key) by calling GsonBuilder's enableComplexMapKeySerialization().

 

 

 

Three, one-to-many reference example

The following example provides a one-to-many mapping relationship between User (employee) and Dept (department)

User entity class:

package com.ickes.json.daomain;

import java.util.Date;

/**
 * @author Ickes
 */
public class User {
	private String userName;
	private String userPwd;
	private Integer age;
	private Date    birthday;
	
	public User(String userName, String userPwd, Integer age, Date birthday) {
		super();
		this.userName = userName;
		this.userPwd = userPwd;
		this.age = age;
		this.birthday = birthday;
	}
	get()和set()方法省略.....!
	@Override
	public String toString() {
		return "User [userName=" + userName + ", userPwd=" + userPwd + ", age="
				+ age + ", birthday=" + birthday + "]";
	}
	
}

    Dept实体类:

   

package com.ickes.json.daomain;

import java.util.List;

public class Dept {
	private String id;
	private String deptName;
	private List<User> users;
	
	public Dept(String id, String deptName) {
		super();
		this.id = id;
		this.deptName = deptName;
	}
	get()和set()方法省略......!
	@Override
	public String toString() {
		return "Dept [id=" + id + ", deptName=" + deptName + ", users=" + users
				+ "]";
	} 
	
	
}

    测试实体类:

   

package com.ickes.json.daomain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
 * Gson处理这种一对多的序列化
 * @author Ickes
 *
 */
public class DeptTest {
	public static void main(String[] args) {
		User user1 = new User("xl","xl_223",12100,new Date());
		User user2 = new User("x2","xl_323",12300,new Date());
		User user3 = new User("x3","xl_423",12300,new Date());
		Dept dept = new Dept("D001","技术预研部");
		List<User> users = new ArrayList<User>();
		users.add(user1);
		users.add(user2);
		users.add(user3);
		dept.setUsers(users);
		
		Gson gson = new GsonBuilder()
		.setPrettyPrinting()
		.setDateFormat("yyyy-MM-dd HH:mm:ss")
		.create();
		String json=gson.toJson(dept);
		System.out.println("一对多的序列化:\n"+json);
		
		dept = gson.fromJson(json,Dept.class);
		System.out.println("一对多的反序列化:\n"+dept);
		
	}
}

   返回结果如下:

一对多的序列化:
{
  "id": "D001",
  "deptName": "技术预研部",
  "users": [
    {
      "userName": "xl",
      "userPwd": "xl_223",
      "age": 12100,
      "birthday": "2015-01-13 18:57:23"
    },
    {
      "userName": "x2",
      "userPwd": "xl_323",
      "age": 12300,
      "birthday": "2015-01-13 18:57:23"
    },
    {
      "userName": "x3",
      "userPwd": "xl_423",
      "age": 12300,
      "birthday": "2015-01-13 18:57:23"
    }
  ]
}
一对多的反序列化:
Dept [id=D001, deptName=技术预研部, 
users=[User [userName=xl, userPwd=xl_223, age=12100, birthday=Tue Jan 13 18:57:23 CST 2015], 
       User [userName=x2, userPwd=xl_323, age=12300, birthday=Tue Jan 13 18:57:23 CST 2015],
       User [userName=x3, userPwd=xl_423, age=12300, birthday=Tue Jan 13 18:57:23 CST 2015]
       ]]

 

 四、带泛型的list集合处理

 

public static void main(String[] args) {
		Gson gson = new Gson();
		String json="[{'last':'xiao','next':'ming'},{'last':'xiao','next':'liang'}]";
		List<Dept> list= null;
		list = gson.fromJson(json,new TypeToken<List<Dept>>(){}.getType());
		for (Dept dept : list) {
			System.out.println(dept);
		}
	}

 返回结果如下:

Dept [last=xiao, next=ming]
Dept [last=xiao, next=liang]

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326385383&siteId=291194637