Java 如何使用JsonReader解析嵌套键和值?

Java 如何使用JsonReader解析嵌套键和值?,java,android,json,api,Java,Android,Json,Api,我正在学习Java,我正在尝试制作一个Fortnite统计跟踪应用程序。我正在使用Fortnite tracker API和JsonReader读取返回的键和值。这很好,但问题是像“杀戮”等统计数据是嵌套的,我不知道如何读取这些数据 我可以使用JsonReader读取嵌套键和值吗? 我尝试了JSONObject,但我不能完全确定我是否正确使用了它,所以我没有走多远 { "accountId": "c48bb072-f321-4572-9069-1c551d074949", "platfo

我正在学习Java,我正在尝试制作一个Fortnite统计跟踪应用程序。我正在使用Fortnite tracker API和
JsonReader
读取返回的键和值。这很好,但问题是像“杀戮”等统计数据是嵌套的,我不知道如何读取这些数据

我可以使用
JsonReader
读取嵌套键和值吗? 我尝试了
JSONObject
,但我不能完全确定我是否正确使用了它,所以我没有走多远

{   "accountId": "c48bb072-f321-4572-9069-1c551d074949",   "platformId": 1,   "platformName": "xbox",   "platformNameLong": "Xbox",   "epicUserHandle": "playername",   "stats": {
    "p2": {
      "trnRating": {
        "label": "TRN Rating",
        "field": "TRNRating",
        "category": "Rating",
        "valueInt": 1,
        "value": "1",
        "rank": 852977,
        "percentile": 100.0,
        "displayValue": "1"
      },
      "score": {
        "label": "Score",
        "field": "Score",
        "category": "General",
        "valueInt": 236074,
        "value": "236074",
        "rank": 6535595,
        "percentile": 3.0,
        "displayValue": "236,074"
      }
上面是我提取的信息示例,以便您可以看到结构

public class MainActivity extends AppCompatActivity {

    TextView tv;
    TextView tv2;
    TextView tv3;
    Button submit;
    EditText tbplatform;
    EditText tbhandle;
    String TAG = "TESTRUN";
    String id = "";

    InputStreamReader responseBodyReader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tvOne);
        tv2 = (TextView) findViewById(R.id.tvTwo);
        tv3 = (TextView) findViewById(R.id.tvThree);
        submit = (Button) findViewById(R.id.btnSubmit);
        tbplatform = (EditText) findViewById(R.id.tbPlatform);
        tbhandle = (EditText) findViewById(R.id.tbHandle);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String platform = String.valueOf(tbplatform.getText());
                final String username = String.valueOf(tbhandle.getText());

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                // All your networking logic
                // should be here

                // Create URL
                URL githubEndpoint = null;
                try {
                    githubEndpoint = new URL("https://api.fortnitetracker.com/v1/profile/" + platform+ "/" + username);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                // Create connection
                HttpsURLConnection myConnection = null;
                try {
                    myConnection =
                            (HttpsURLConnection) githubEndpoint.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                myConnection.setRequestProperty("TRN-Api-Key", "API_KEY_HERE");

                try {
                    if (myConnection.getResponseCode() == 200) {
                        InputStream responseBody = myConnection.getInputStream();
                        responseBodyReader =
                                new InputStreamReader(responseBody, "UTF-8");


                        JsonReader jsonReader = new JsonReader(responseBodyReader);


                        jsonReader.beginObject(); // Start processing the JSON object

                        while (jsonReader.hasNext()) { // Loop through all keys
                            final String key = jsonReader.nextName(); // Fetch the next key

                            //Log.v(TAG, key);

                            if (key.equals("epicUserHandle") || key.equals("platformName") || key.equals("accountId")) { // Check if desired key
                                // Fetch the value as a String
                                final String value = jsonReader.nextString();

                                if (key.equals("epicUserHandle")) {
                                    Log.v(TAG, "Gamertag: " + value);


                                }
                                if (key.equals("platformName")) {
                                    Log.v(TAG, "Console: " + value);
                                }
                                if (key.equals("stats")) {

                                    Log.v(TAG, "Kills: " + value);
                                }

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        //stuff that updates ui
                                        if(key.equals("epicUserHandle")) {
                                            tv.setText("Username: " + value);
                                        }
                                        if(key.equals("platformName")) {
                                            tv2.setText("Platform: " +value);
                                        }
                                        if(key.equals("accountId")) {
                                            tv3.setText("Account ID: " +value);
                                        }
                                    }
                                });
                                //Log.v(TAG, "" +value);

                                // Do something with the value
                                // ...

                                //break; // Break out of the loop
                            } else {
                                jsonReader.skipValue(); // Skip values of other keys
                            }

                        }

                        jsonReader.close();

                        myConnection.disconnect();
                    } else {
                        // Error handling code goes here
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
     }
    });
    }
}

我想这可能会对你有所帮助

您需要创建一些类,如下所示

如果您的回答与问题中的解释相同。这样就行了


我认为使用谷歌gson是更好的选择。它很容易使用。@Abhishek谢谢,我一直在尝试使用GSON。我已经设置了类、getter和setter,但我以前从未使用过,所以我在从httprequest获取信息以显示时遇到了问题。谢谢。我现在正在尝试。然而,我只是有点困惑,
Response-Response-Response=new Gson().fromJson(Response-Response,Response.class)@Brandan我做了改变。它应该是完整的响应。
class Score implements Serializable {
private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;

public Score() {
    this("", "", "", 0, "", 0, 0.0, "");
}

public Score(String label, String field,
             String category, Integer valueInt,
             String value, Integer rank,
             Double percentile, String displayValue) {
    this.label = label;
    this.field = field;
    this.category = category;
    this.valueInt = valueInt;
    this.value = value;
    this.rank = rank;
    this.percentile = percentile;
    this.displayValue = displayValue;
}

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getField() {
    return field;
}

public void setField(String field) {
    this.field = field;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public Integer getValueInt() {
    return valueInt;
}

public void setValueInt(Integer valueInt) {
    this.valueInt = valueInt;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public Integer getRank() {
    return rank;
}

public void setRank(Integer rank) {
    this.rank = rank;
}

public Double getPercentile() {
    return percentile;
}

public void setPercentile(Double percentile) {
    this.percentile = percentile;
}

public String getDisplayValue() {
    return displayValue;
}

public void setDisplayValue(String displayValue) {
    this.displayValue = displayValue;
}
}

class TRNRating implements Serializable {

private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;

public TRNRating() {
    this("", "", "", 0, "", 0, 0.0, "");
}

public TRNRating(String label, String field,
                 String category, Integer valueInt,
                 String value, Integer rank,
                 Double percentile, String displayValue) {
    this.label = label;
    this.field = field;
    this.category = category;
    this.valueInt = valueInt;
    this.value = value;
    this.rank = rank;
    this.percentile = percentile;
    this.displayValue = displayValue;
}

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getField() {
    return field;
}

public void setField(String field) {
    this.field = field;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public Integer getValueInt() {
    return valueInt;
}

public void setValueInt(Integer valueInt) {
    this.valueInt = valueInt;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public Integer getRank() {
    return rank;
}

public void setRank(Integer rank) {
    this.rank = rank;
}

public Double getPercentile() {
    return percentile;
}

public void setPercentile(Double percentile) {
    this.percentile = percentile;
}

public String getDisplayValue() {
    return displayValue;
}

public void setDisplayValue(String displayValue) {
    this.displayValue = displayValue;
}
}

class P2 implements Serializable {
private TRNRating trnRating;
private Score score;

public P2() {
    this(new TRNRating(), new Score());
}

public P2(TRNRating trnRating, Score score) {
    this.trnRating = trnRating;
    this.score = score;
}

public TRNRating getTrnRating() {
    return trnRating;
}

public void setTrnRating(TRNRating trnRating) {
    this.trnRating = trnRating;
}

public Score getScore() {
    return score;
}

public void setScore(Score score) {
    this.score = score;
}
}

class Stats implements Serializable {
private P2 p2;

public Stats() {
    this(new P2());
}

public Stats(P2 p2) {
    this.p2 = p2;
}
}

//You Need To Change Name Of This Class
class Response implements Serializable {
private String accountId;
private Integer platformId;
private String platformName;
private String platformNameLong;
private String epicUserHandle;
private Stats stats;

public Response() {
    this("", 0, "", "", "", new Stats());
}

public Response(String accountId, Integer platformId,
                String platformName, String platformNameLong,
                String epicUserHandle, Stats stats) {
    this.accountId = accountId;
    this.platformId = platformId;
    this.platformName = platformName;
    this.platformNameLong = platformNameLong;
    this.epicUserHandle = epicUserHandle;
    this.stats = stats;
}

public String getAccountId() {
    return accountId;
}

public void setAccountId(String accountId) {
    this.accountId = accountId;
}

public Integer getPlatformId() {
    return platformId;
}

public void setPlatformId(Integer platformId) {
    this.platformId = platformId;
}

public String getPlatformName() {
    return platformName;
}

public void setPlatformName(String platformName) {
    this.platformName = platformName;
}

public String getPlatformNameLong() {
    return platformNameLong;
}

public void setPlatformNameLong(String platformNameLong) {
    this.platformNameLong = platformNameLong;
}

public String getEpicUserHandle() {
    return epicUserHandle;
}

public void setEpicUserHandle(String epicUserHandle) {
    this.epicUserHandle = epicUserHandle;
}

public Stats getStats() {
    return stats;
}

public void setStats(Stats stats) {
    this.stats = stats;
}
}
//In your code after status check you need to do like this
if (myConnection.getResopnseCode() == 200) {
    BufferedReader br=new BufferedReader(responseBodyReader);
    String read = null, entireResponse = "";
    StringBuffer sb = new StringBuffer();
    while((read = br.readLine()) != null) {
        sb.append(read);
    }
    entireResponse = sb.toString();

    //You need to change name of response class
    Response response = new Gson().fromJson(entireResponse , Response.class);

}