fastjson 学习总结

前端之家收集整理的这篇文章主要介绍了fastjson 学习总结前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.pom.xml里引入jar包

    <!-- 阿里巴巴高性能json开发包 -->
 	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.3</version>
	</dependency>



2.新建一个User类
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; }
}
3.新建一个Group类
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; }
}

4. 编写测试类
public class Main {

	public static void main(String[] args) {
		Group group = new Group();
		group.setId(0L);
		group.setName("admin");

		User guestUser = new User();
		guestUser.setId(2L);
		guestUser.setName("guest");

		User rootUser = new User();
		rootUser.setId(3L);
		rootUser.setName("root");

		group.getUsers().add(guestUser);
		group.getUsers().add(rootUser);

		String jsonString = JSON.toJSONString(group);

		System.out.println(jsonString);
		
		Group group2 = JSON.parSEObject(jsonString,Group.class);
		System.out.println(group2.getName());
		
		String jsonStr = "{\"name\":\"兰溪小城\",\"sex\":\"1\",\"mobile\":\"1234567890\"}" ; 
		JSONObject jsonObject = JSONObject.parSEObject(jsonStr) ;  
		System.out.println(jsonObject.get("name"));
		
		String jsonStr1 = "[{\"name\":\"兰溪小城\",\"mobile\":\"1234567890\"}]" ; 
		JSONArray jsonArray = JSONArray.parseArray(jsonStr1);
		System.out.println(jsonArray.get(0));
	}

}
5. fastjson 解析json字符串为四种类型
     (1) JavaBean
         Person person = JSON.parSEObject(jsonString,Person.class);

     (2) List<JavaBean>
         List<Person> listPerson =JSON.parseArray(jsonString,Person.class);

     (3) List<String>
         List<String> listString = JSON.parseArray(jsonString,String.class);

     (4) List<Map<String,Object>>
         List<Map<String,Object>> listMap = JSON.parSEObject(jsonString,new TypeReference<List<Map<String,Object>>>(){}); 
原文链接:https://www.f2er.com/json/289323.html

猜你在找的Json相关文章