1.首先引入json jar包
net.sf.json-lib
json-lib
2.4
jdk15
2.创建user类
package com.lc.node.cloud.model;
import java.io.Serializable;
import java.util.Date;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonFormat;
1.创建User类
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private String password;
private String username;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
2.实现java对象与Json字符串之间的转化
public class UserTest {
public static void main(String[] args) {
// 实现java对象与Json字符串之间的转化
// 2. User对象与json之间的转换
//2.1 将User对象转成json
User u = new User();
u.setUserName("xiaoming");
u.setPassWord("0000")
JSONObject obj = JSONObject.fromObject(u);
System.out.println("将User对象转成json:" + obj);
//2.2 将json字符串转成User对象
u =(User)JSONObject.toBean(obj,User.class);
System.err.println(u.getUserName());
}
}
3.java List集合与json之间的转换
public class UserListTest {
public static void main(String[] args) {
// 3. 将List与json之间的转换
//3.1 将List转成json
User user = new User ();
user.setUserName("00001");
User user2 = new User ();
user2.setUserName("00002");
List datas = new ArrayList();
datas.add(user );
datas.add(user2 );
JSONArray jArray = JSONArray.fromObject(datas);
System.err.println(jArray.get(0));
// 3.3. 将json字符串转成List对象
datas = JSONArray.toList(jArray, User.class);
System.err.println(datas.get(0).getUserId());
}
}
4..java Map集合与json之间的转换
public class UserListTest {
public static void main(String[] args) {
// 4. 将Map对象与json之间的转换
// 4.1 将Map转成json
User user = new User ();
user.setUserName("00001");
User user2 = new User ();
user2.setUserName("00002");
Map map = new HashMap();
map.put("user1", dataTemplate);
map.put("user2", dataTemplates);
JSONObject myJson = JSONObject.fromObject(map);
System.err.println(myJson.toString());
// 4.2.将json字符串转成map
Map map2 = myJson;
dataTemplates = (DeleteData) map.get("user2");
System.err.println(dataTemplates.getUserId());
System.err.println(jArray.get(0));
}
}
标签:fastjson,java,String,json,Json,User,println,new,public
来源: https://www.cnblogs.com/liuhaoking/p/12722096.html