1 回答

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
public static void jsonStrToJava(){
//定義兩種不同格式的字符串
String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城區(qū)\"}";
String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城區(qū)\"}]";
//1、使用JSONObject
JSONObject jsonObject=JSONObject.fromObject(objectStr);
Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
//2、使用JSONArray
JSONArray jsonArray=JSONArray.fromObject(arrayStr);
//獲得jsonArray的第一個(gè)元素
Object o=jsonArray.get(0);
JSONObject jsonObject2=JSONObject.fromObject(o);
Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
System.out.println("stu:"+stu);
System.out.println("stu2:"+stu2);
}
添加回答
舉報(bào)