java - 如何使用 JsonReader 解析嵌套的键和值?

标签 java android json api

我正在学习 Java,并且正在尝试制作一个 Fortnite 统计跟踪应用程序。我正在使用 Fortnite 跟踪器 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();
                }
            }
        });
     }
    });
    }
}

最佳答案

我想这可能对你有帮助

You Need To Create Some Classes As Given Below

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;
}
}

If your response is same as explained in question. Then this will work.

//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);

}

关于java - 如何使用 JsonReader 解析嵌套的键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752576/

相关文章:

java - Spring Webflow : binding does not work with map although map values are in the httprequest

java - 为什么非strictfp模式下的转换被认为是丢失信息的转换?

java - 清理java代码,多个if语句

android - ListView 内的按钮操作

json - 使用 bash 发送 json HTTP post

java - android:layout_alignParentBottom ="true"和android:gravity ="bottom"似乎对RelativeLayout没有影响

android - 如何在 ScrollView 下放置新项目

java - 按钮文本需要根据 EditText 输入的数据进行更改

json - 第 1 行解析错误 : { #networkports "l ----------^ Expecting ' STRING', '}'

json - 在 Golang 中初始化和插入嵌套的 JSON 数据?