JSONObject使用示例

引入org.json包

//1.直接构建
JSONObject obj = new JSONObject();
obj.put(key, value);
String json = obj.toString();
//put()方法的第一个参数为key值,必须为String类型,
//第二个参数为value,可以为Object、Map、Collection、boolean以及double、int、long等。
//double以及int等类型只是在Java中,写入到json中时,统一都会以Number类型存储。

//2.1使用map构建
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "scott");
map.put("sex", "male");
map.put("age", 24);
map.put("hobbies", new String[] {"hiking", "swimming"});
JSONObject obj = new JSONObject(map);
String json = obj.toString();
//2.2使用JavaBean构建(JavaBean必须提供getter())
Person person = new Person("scott","male",24,new String[] {"hiking", "swimming"});
JSONObject obj = new JSONObject(person);
String json = obj.toString();

//3.1对基本数据类型的解析
String jsonStr = "...";
JSONObject obj = new JSONObject(content);
String name = obj.getString("name");
String sex = obj.getString("sex");
String age = obj.getString("age");
//3.2对数组的解析
JSONArray hobbies = obj.getJSONArray("hobbies");
for (int i = 0; i < hobbies.length(); i++) {
    String s = (String) hobbies.get(i);
    System.out.println(s);
}




猜你喜欢

转载自blog.csdn.net/tt_fan/article/details/82734636