String str ="{'person':'oneself','info':{'name':'小王','age':22},'people':[{'a':'Brett','b':'McLaughlin','c':'aaaa'},{'a':'Jason','b':'Hunter','c':'bbbb'},{'a':'Elliotte','b':'Harold','c':'cccc'}]}";
JSONObject jsonObj = JSONObject.fromObject(str);
String person = jsonObj.getString("person");
System.out.println("获取字符person:"+person);
JSONObject info = jsonObj.getJSONObject("info");
System.out.println("获取对象info :(name:"+info.getString("name")+" age:"+info.getString("age")+")");
System.out.println("获取数组people:");
JSONArray arr = jsonObj.getJSONArray("people");
for (int i = 0; i < arr.size(); i++) {
JSONObject o = arr.getJSONObject(i);
String a = (String) o.get("a");
String b = (String) o.get("b");
String c = (String) o.get("c");
System.out.println(a+"|"+b+"|"+c);
}
//Ajax请求带参Json数据
//var jsonArr = new Array();
//var str = JSON.stringify(jsonArr); ==》JSON数组转字符串(对象同理)
String gradeString ="[{'a':'a1','b':'b1','c':'c1'},{'a':'a2','b':'b2','c':'c2'},{'a':'a3','b':'b3','c':'c3'}]";
JSONArray jsonArr = JSONArray.fromObject(gradeString); //此处为null,或者会直接报错
System.out.println("解析Ajax请求传来的Json数组:");
for (int i = 0; i < jsonArr.size(); i++) {
JSONObject o = jsonArr.getJSONObject(i);
String a = (String) o.get("a");
String b = (String) o.get("b");
String c = (String) o.get("c");
System.out.println(a+"|"+b+"|"+c);
}
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
String message = "{'method':'test','params':{'id':'1','name':'小明','description':'翻滚吧!'}}";
System.out.println("message:"+message);
JSONObject jsonObject = JSONObject.fromObject(message); //字符转换为JSON对象
JSONObject paramsJSON = jsonObject.getJSONObject("params"); //获取JSON对象内容
System.out.println("paramsJSON.toString():"+paramsJSON.toString());
//json字符转Java对象方法一:(fastjson.jar)
Model model1 =JSON.parseObject(paramsJSON.toString(),Model.class);
System.out.println("parseObject:"+model1.toString());
//json字符转Java对象方法二:(fastjson.jar)
JSON json = JSON.parseObject(paramsJSON.toString());
Model model2 = JSON.toJavaObject(json, Model.class);
System.out.println("toJavaObject:"+model2.toString());
//json字符转Java对象方法三:(json.jar)
JSONObject obj = JSONObject.fromObject(json);
Model model3=(Model) JSONObject.toBean(obj, Model.class);
System.out.println("toBean:"+model3);
//java对象转JSONObject 集合转JSONArray 字符对象转JSONObject 都用fromObject
JSONObject jb = JSONObject.fromObject(model1);
System.out.println("javaToJson:"+jb.toString());
public class Model{int id;String name;String description;}
/**
* 封装将json对象转换为java集合对象
*/
@SuppressWarnings({ "unused", "unchecked" })
private <T> List<T> getJavaList(T clazz, String jsons) {
List<T> objs=null;
JSONArray jsonArray=(JSONArray)JSONSerializer.toJSON(jsons);
if(jsonArray!=null){
objs=new ArrayList<T>();
List<T> list=(List<T>)JSONSerializer.toJava(jsonArray);
for(Object o:list){
JSONObject jsonObject=JSONObject.fromObject(o);
T obj=(T)JSONObject.toBean(jsonObject, clazz.getClass());
objs.add(obj);
}
}
return objs;
}