首页 > 代码库 > fastjson 的简单使用
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; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。