java对象与json字符串的互相转换
java对象与json字符串的互相转换
1.采用 net.sf.json.JSONObject
maven依赖包:
1 <dependency> 2 <groupId>net.sf.json-lib</groupId> 3 <artifactId>json-lib</artifactId> 4 <version>2.4</version> 5 <classifier>jdk15</classifier> 6 </dependency>
java对象转换为json字符串:
1 import net.sf.json.JSONObject; 2 3 public String ObjectToJsonStr(){ 4 UserName userName = new UserName(); 5 userName.setName("hahaha"); 6 JSONObject json = JSONObject.fromObject(userName);//将java对象转换为json对象 7 String str = json.toString();//将json对象转换为json字符串 8 return str; 9 }
json字符串转换为java对象:
1 import net.sf.json.JSONObject; 2 3 public UserName JsonStrToObject(String str){ 4 JSONObject obj = new JSONObject().fromObject(str);//将json字符串转换为json对象 5 UserName userName = (UserName)JSONObject.toBean(obj,UserName.class);//将json对象转换为java对象 6 return userName; 7 }
2.采用 com.alibaba.fastjson.JSON
maven依赖包:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.39</version> </dependency>
java对象转换为json字符串:
1 import com.alibaba.fastjson.JSON; 2 3 public String ObjectToJsonStr(UserName userName){ 4 String str = JSON.toJSONString(userName); 5 return str; 6 }
json字符串转换为java对象:
1 import com.alibaba.fastjson.JSON; 2 3 public UserName JsonStrToObject(String str){ 4 UserName userName = JSON.parseObject(str, UserName.class);//将json字符串转换为java对象 5 return userName; 6 }
程序员的眼里,不止有代码和bug,还有诗与远方和妹子!!!