【转】JSON字符串与Java对象的相互转换

注意:本文中代码使用时所有的“《”需转换为左括号,“》”需转换为右括号
所用Java包:json-lib
Maven代码:
 《dependency》
  《groupId》net.sf.json-lib《/groupId》
  《artifactId》json-lib《/artifactId》
  《version》2.4《/version》
  《classifier》jdk15《/classifier》
 《/dependency》

如果有类定义为:
public class CollectionCircleMessage {
 
 private Integer messageId;
 
 private String userId;
 
 private String nickname;
 
 private String portrait;
 
 private RudderMessage rudderMessage;
 
 private List《CollectionUserComment》 rudderCircleComments;
 
 private List《CollectionUserAttention》 rudderAttention;
}


1.将Java对象(JSONObject)转换为Json字符串
JSONObject.fromObject(collectionCircleMessage).toString();


2.将Java对象列表(JSONArray)转换为Json字符串
JSONArray.fromObject(collectionCircleMessage).toString();


3.将Json字符串转换为Java对象
JSONObject jSONObject = JSONObject.fromObject(jsonString);
CollectionCircleMessage collectionCircleMessagesList = (CollectionCircleMessage)JSONObject.toBean(jSONObject, CollectionCircleMessage.class);

如果有复杂对象:
JSONObject jSONObject = JSONObject.fromObject(jsonString);
Map《String, Class》 classMap = new HashMap《String, Class》();
classMap.put("rudderCircleComments", CollectionUserComment.class);
classMap.put("rudderAttention", CollectionUserAttention.class);
CollectionCircleMessage collectionCircleMessages = (CollectionCircleMessage)JSONObject.toBean(jSONObject, CollectionCircleMessage.class,classMap);

否则会出现
 net.sf.ezmorph.bean.MorphDynaBean cannot be cast to XXX的错误


4.将Json字符串转换为Java对象列表
JSONArray jsonArray = JSONArray.fromObject(jsonString);
List《CollectionCircleMessage》 collectionCircleMessagesList = (List《CollectionCircleMessage》)JSONArray.toCollection(jsonArray, CollectionCircleMessage.class);

如果有复杂对象:
JSONArray jsonArray = JSONArray.fromObject(jsonString);
Map《String, Class》 classMap = new HashMap《String, Class》();
classMap.put("rudderCircleComments", CollectionUserComment.class);
classMap.put("rudderAttention", CollectionUserAttention.class);
List《CollectionCircleMessage》 collectionCircleMessagesList = (List《CollectionCircleMessage》)JSONArray.toList(jsonArray, CollectionCircleMessage.class,classMap);

否则会出现
 net.sf.ezmorph.bean.MorphDynaBean cannot be cast to XXX的错误

你可能感兴趣的:(java,java)