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

时间:2018-04-10 11:33:46

标签: 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();
                }
            }
        });
     }
    });
    }
}

1 个答案:

答案 0 :(得分:1)

我认为这可能会对您有所帮助

  

你需要创建下面给出的一些类

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

}