java对象与json字符串的互相转换

时间:2021-08-03 01:31:18

java对象与json字符串的互相转换

1.采用 net.sf.json.JSONObject

maven依赖包:

 <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

java对象转换为json字符串:

 import net.sf.json.JSONObject;

 public String ObjectToJsonStr(){
UserName userName = new UserName();
userName.setName("hahaha");
JSONObject json = JSONObject.fromObject(userName);//将java对象转换为json对象
String str = json.toString();//将json对象转换为json字符串
return str;
}

json字符串转换为java对象:

 import net.sf.json.JSONObject;

 public UserName JsonStrToObject(String str){
JSONObject obj = new JSONObject().fromObject(str);//将json字符串转换为json对象
UserName userName = (UserName)JSONObject.toBean(obj,UserName.class);//将json对象转换为java对象
return userName;
}

2.采用 com.alibaba.fastjson.JSON

maven依赖包:

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>

java对象转换为json字符串:

 import com.alibaba.fastjson.JSON;

 public String ObjectToJsonStr(UserName userName){
String str = JSON.toJSONString(userName);
return str;
}

json字符串转换为java对象:

 import com.alibaba.fastjson.JSON;

 public UserName JsonStrToObject(String str){
UserName userName = JSON.parseObject(str, UserName.class);//将json字符串转换为java对象
return userName;
}