1.json格式
String str="{name:‘huahua’,age:25,address:{description:‘hhh’,floor:10},like:[‘a’,‘b’,‘c’]}";
首先,将这整个字符串转换为对象; JSONObject jsonObj=new JSONObject(str);
其次,分析格式( 属于键值对的格式 )
name是key 'huahua’是String 类型的value;
我们可以用 jsonObj.getString(“name”);
address是key 后面的两个键值对可以看成一个对象;
我们可以用 jsonObj.getJSONObject(“address”);
like是key 后面是一个array格式
我们可以用 jsonObj.getJSONArray(“like”);
package com.company.cubademo.core.controller;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
class Test{
public static void main(String[] args)
{
/*
1.将下面的JSON字符串 解析并打印出来
*/
String str="{name:'huahua',age:25,address:{description:'hhh',floor:10},like:['a','b','c']}";
//JSONObject 解析
try
{
JSONObject jsonObj=new JSONObject(str);
String name=jsonObj.getString("name");
int age=jsonObj.getInt("age");
System.out.println(name+","+age);
//地址是 JSONObject
JSONObject addressObj=jsonObj.getJSONObject("address");
String description=addressObj.getString("description");
int floor=addressObj.getInt("floor");
System.out.println(description+","+floor);
//爱好是 JSONArray
JSONArray likeArray=jsonObj.getJSONArray("like");
for(int i=0;i<likeArray.length();i++)
{
String value=likeArray.getString(i);
System.out.println(value);
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}