目录
使用com.alibaba.fastjson解析
总结:一个花括号 { 放进JSONObject一次
一个中括号 [ 放进JSONArray一次
获取一次属性调用getXxx一次
1.普通元素
getXxx()直接获取
String jsonString = "{'name':'卢本伟','age':24}";
JSONObject json = JSON.parseObject(jsonString);
String name = json.getString("name");
int age = json.getIntValue("age");
System.out.println(name);
System.out.println(age);
2.属性包含大括号 {
先使用getJSONObject()获取JSONObject对象 , 然后进一步getXxx()解析属性
String jsonString = "{'Hero':{'name':'Fizz','position':'Mid','charactor':'killer'}}";
JSONObject jsonObject = JSON.parseObject(jsonString);
JSONObject Hero = jsonObject.getJSONObject("Hero");
String name = Hero.getString("name");
String position = Hero.getString("position");
String charactor = Hero.getString("charactor");
System.out.println(name + "..." + position + "..." + charactor);
3.属性包含中括号 [
先使用getJSONArray()获取JSONArray对象,然后进一步遍历
String jsonString = "{'nickNames':['五五开','芦苇','white']}";
JSONObject jsonObject = JSON.parseObject(jsonString);
JSONArray nickNames = jsonObject.getJSONArray("nickNames");
for(Object nickName:nickNames){
System.out.println(nickName);
}
4.属性中既有中括号包括,又嵌套了大括号
一层层获取即可:先getJSONArray,然后getJSONObject,到了属性,就是getXxx()
String jsonString = "{'Honors':[{'year':2011,'name':'TGA总决赛冠军'},{'year':2013,'name':'S3全球总决赛中国区冠军'},{'year':2013,'name':'S3全球总决赛亚军'}]}";
JSONObject jsonObject = JSON.parseObject(jsonString);
JSONArray honors = jsonObject.getJSONArray("Honors");
for(int i=0; i<honors.size(); i++){
JSONObject honor = (JSONObject) honors.get(i);
int year = honor.getIntValue("year");
String name = honor.getString("name");
System.out.println(year + "..." + name);
}