Java gets the data in Json

Table of contents

1. Common elements

2. The attribute contains braces { 

3. The attribute contains square brackets [

4. There are both square brackets and nested curly brackets in the attribute


Use com.alibaba.fastjson to parse

Summary: A curly brace { put into JSONObject once

           A square bracket [ put into JSONArray once

           Get an attribute and call getXxx once

1. Common elements

getXxx() get directly

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. The attribute contains braces { 

First use getJSONObject() to get the JSONObject object, and then further getXxx() to parse the properties

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. The attribute contains square brackets [

First use getJSONArray() to get the JSONArray object, and then traverse further

String jsonString = "{'nickNames':['五五开','芦苇','white']}";
JSONObject jsonObject = JSON.parseObject(jsonString);
JSONArray nickNames = jsonObject.getJSONArray("nickNames");
for(Object nickName:nickNames){
    System.out.println(nickName);
}

4. There are both square brackets and nested curly brackets in the attribute

You can get it layer by layer: first getJSONArray, then getJSONObject, and when it comes to attributes, it is 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);
}

Guess you like

Origin blog.csdn.net/weixin_60968208/article/details/129044144