int age = jsonObject.getInt("age");
String gender = jsonObject.getString("gender");
String grades = jsonObject.getString("grades");
String name = jsonObject.getString("name");
float weight = (float) jsonObject.getDouble("weight");
System.out.println(age);
System.out.println(gender);
System.out.println(grades);
System.out.println(name);
System.out.println(weight);
}
}
说明:
这种方式不需要我们定义的变量名跟Json字符串中的元素名相同,如我们也可以这样String studentName = jsonObject.getString(“name”);
如果我们取的元素在Json字符串中不存在的话,会报错;
如果我们取的元素类型跟接收的类型不同的话,可能会报错;
第三种方法:用迭代器迭代输出
package com.test;
import java.util.Iterator;
import net.sf.json.JSONObject;
public class Domain {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
String jsonStr = "{\"age\":20,\"gender\":\"male\",\"grades\":\"三班\",\"name\":\"苏三\",\"weight\":63.5}";
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Iterator keys = jsonObject.keys();
String key = null;
Object value = null;
while(keys.hasNext()){
key = (String) keys.next();
value = jsonObject.get(key);
System.out.println("key:"+key+" value:"+value.toString());
}
}
}
说明:
通过这种迭代,能将所有的元素都获取到;
用迭代的方式我们无法提前定义到每种元素对应value的类型。
最后,我们来看一下,怎么反向通过Student类来生成一个Json字符串
package com.test;
import net.sf.json.JSONObject;
import com.bean.Student;
public class Domain {
public static void main(String[] args) {
Student stu = new Student();
stu.setAge(25);
stu.setGender("female");
stu.setGrades("一班");
stu.setName("露西");
stu.setWeight(51.3f);
String jsonStr = JSONObject.fromObject(stu).toString();
System.out.println(jsonStr);
}
}
生成的字符串为:
{"age":25,"gender":"female","grades":"一班","name":"露西","weight":51.3}