fastJSON例子3

前端之家收集整理的这篇文章主要介绍了fastJSON例子3前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.ylchou.testfastjson;

public class User {

	private Long id;
	private String name;
	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;
	}
	
}

package com.ylchou.testfastjson;

import java.util.ArrayList;
import java.util.List;

public class Group {

	private Long id;
	private String name;
	private List<User> users = new ArrayList<User>();
	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 List<User> getUsers() {
		return users;
	}
	public void setUsers(List<User> users) {
		this.users = users;
	}
	
	
}

package com.ylchou.testfastjson;

import com.alibaba.fastjson.JSON;

public class TestFastJSON3 {

	public static void main(String[] args) {
		
		Group group = new Group();
		User users = new User();
		User users2 = new User();
		User users3 = new User();
		
		users.setId(1L);
		users.setName("ylchou");
		
		users2.setId(2L);
		users2.setName("chousoul");
		
		users3.setId(3L);
		users3.setName("shayue");
		
		group.setId(7L);
		group.setName("gongsi");
		group.getUsers().add(users);//注意
		group.getUsers().add(users2);//注意
		group.getUsers().add(users3);
//		group.getUsers().add(users3);//重复不会得到想要的
		
		String groupJsonString = JSON.toJSONString(group);
		System.out.println("encode:"+groupJsonString);
		
		Group classGroup = JSON.parSEObject(groupJsonString,Group.class);
		System.out.println("discode:"+classGroup);
		
		Object classGroup2 = JSON.parSEObject(groupJsonString,Group.class);
		System.out.println("discode:"+classGroup2);
		
		//得到的仍然是JSON,所有parSEObject中参数要为转化后的类.class,不能为Object.class。
		Object classGroup3 = JSON.parSEObject(groupJsonString,Object.class);
		System.out.println("discode:"+classGroup3);
		
	}

控制台打印:

encode:{"id":7,"name":"gongsi","users":[{"id":1,"name":"ylchou"},{"id":2,"name":"chousoul"}]} discode:com.ylchou.testfastjson.Group@182f0db discode:com.ylchou.testfastjson.Group@192d342 discode:{"id":7,"name":"chousoul"}]} encode:{"id":7,"name":"chousoul"},{"id":3,"name":"shayue"},{"$ref":"$.users[2]"}]} discode:com.ylchou.testfastjson.Group@5224ee discode:com.ylchou.testfastjson.Group@f6a746 discode:{"id":7,null]}

猜你在找的Json相关文章