java生成json总结
Json必备包
commons-beanutils-1.7.0.jar不加这个包
java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean
commons-collections-3.2.jar 不加这个包
java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap
commons-lang-2.3.jar不加这个包
java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
commons-logging-1.0.4.jar不加这个包
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
ezmorph-1.0.6.jar不加这个包
java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher
(本人亲测,没有这个包,myeclipse不抛异常,跟踪执行到JSONObject jsonObj = JSONObject.fromObject(jsonMap);这段代码就中断了,其以后的代码也不执行了,确实没有像网上说的不抛异常)
json-lib-2.1-jdk15.jar不加这个包
java.lang.NoClassDefFoundError: net/sf/json/JSONObject
Java中转换为Json对象的例子
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonUtil {
public void listToJson() {
List<Object> jsonList = new ArrayList<Object>();
jsonList.add("nihao");
jsonList.add("hello");
jsonList.add("haha");
jsonList.add("heihei");
JSONArray jsonArray = JSONArray.fromObject(jsonList);
System.out.println(jsonArray);
}
//输出结果:["nihao","hello","haha","heihei"]
public void mapToJson() {
Map<Object, Object> jsonMap = new HashMap<Object, Object>();
jsonMap.put("name", "Ren");
jsonMap.put("sex", "man");
jsonMap.put("age", 24);
JSONObject jsonObject = JSONObject.fromObject(jsonMap);
System.out.println(jsonObject);
}
//输出结果:{"sex":"man","name":"Ren","age":24}
public void mapAndListToJson() {
JSONArray jsonArr = new JSONArray();
JSONObject jsonObj = new JSONObject();
for(int i = 0; i < 10; i++) {
JSONObject tjo = new JSONObject();
tjo.put("optValue", i+"");
tjo.put("optText", i+"Text");
jsonArr.add(tjo);
}
jsonObj.put("options", jsonArr);
System.out.println(jsonObj);
}
//输出结果:{"options":[{"optValue":"0","optText":"0Text"},{"optValue":"1","optText":"1Text"},{"optValue":"2","optText":"2Text"},{"optValue":"3","optText":"3Text"},{"optValue":"4","optText":"4Text"},{"optValue":"5","optText":"5Text"},{"optValue":"6","optText":"6Text"},{"optValue":"7","optText":"7Text"},{"optValue":"8","optText":"8Text"},{"optValue":"9","optText":"9Text"}]}
}
生成json所需jar包: jar.zip
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。