fastjson 的简单使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fastjson 的简单使用相关的知识,希望对你有一定的参考价值。

	public static void main(String[] args) {
		/*普通对象与json相互转换*/
		User u = new User("miquan", "000");
		
		//{"@type":"testjava.User","password":"000","userName":"miquan"}
		String jsonUser = JSON.toJSONString(u, SerializerFeature.WriteClassName);
		System.out.println(jsonUser);
		
		User user = JSON.parseObject(jsonUser, User.class);
		
		/*带集合的对象与json字符串相互转换*/
		List<String> list = new ArrayList<String>();
		list.add("miquan");
		list.add("qiantu");
		Download d = new Download();
		d.setEmojiSetName("guoqiao");
		d.setEmojiPathList(list);
		
		//{"@type":"testjava.Download","emojiPathList":["miquan","qiantu"],"emojiSetName":"guoqiao"}
		String jsonList = JSON.toJSONString(d, SerializerFeature.WriteClassName);
		System.out.println(jsonList);
		
		Download download = JSON.parseObject(jsonList, Download.class);
		
		/*json与List对象相互转换*/		
		List<User> listUser = new ArrayList<User>();
		listUser.add(new User("liangguoqiao", "iloveyou"));
		listUser.add(new User("liangguoqiao", "iloveyou"));
		
		//[{"password":"iloveyou","userName":"liangguoqiao"},
		//{"password":"iloveyou","userName":"liangguoqiao"}]
		String json = JSON.toJSONString(listUser);
		System.out.println(json);
		
		List<User> users = JSON.parseArray(json, User.class);
	}


注意:1、下载地址

    2、User和Download等实体类必须加入空的构造函数

            3、转为JSON字符串的时候加上SerializerFeature.WriteClassName

            4、坐等下班。。。


package com.yangshidesign.weixinface.bean;

import java.util.List;

public class Download {
	private String emojiSetName;
	/** 表情图片名字 */
	private List<String> emojiNameList;
	
	public Download() {
		super();
	}
	public String getEmojiSetName() {
		return emojiSetName;
	}
	public void setEmojiSetName(String emojiSetName) {
		this.emojiSetName = emojiSetName;
	}
	public List<String> getEmojiNameList() {
		return emojiNameList;
	}
	public void setEmojiNameList(List<String> emojiNameList) {
		this.emojiNameList = emojiNameList;
	}
}

package testjava;

public class User {
	private String userName;
	private String password;
	
	public User() {
		super();
	}
	public User(String userName, String password) {
		super();
		this.userName = userName;
		this.password = password;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


以上是关于fastjson 的简单使用的主要内容,如果未能解决你的问题,请参考以下文章

fastjson 的简单使用

高性能JSON框架之FastJson的简单使用

fastjson简单使用demo,@JSONField注解属性字段上与setget方法上。实体类toString(),实体类转json的区别;_下划线识别

FastJSON 简单使用

深拷贝的最简单实现(使用fastjson)

JSON解析工具——fastjson的简单使用