1

I have this ugly JSON string and I need to get the totalStars which in this case is 500. I have tried quite some solutions but none seem to work.

This is the JSON:

{
  "code": 200,
  "message": "success",
  "data": [
    [
      {
        "totalPosts": 42
      }
    ],
    [
      {
        "totalStars": 500
      }
    ],
    [
      {
        "followingCount": 1
      }
    ],
    [
      {
        "followerCount": 1
      }
    ]
  ]
}

And at the moment I'm trying to get the data with this:

JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
    String[] names = new String[data.length()];
    for(int i = 0 ; i < data.length() ; i++) {
        names[i] = data.getString(i);

    }
    System.out.println(names);
}

The JSONArray data contains the correct data, but I cant seem to get the other data out of it.

Richard
  • 1,087
  • 18
  • 52

2 Answers2

2

It looks like your data is an array of array of objects, not strings. You need to do something like this:

JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
    String[] names = new String[data.length()];
    for(int i = 0 ; i < data.length() ; i++) {
        JSONArray arr = data.getJSONArray(i);
        dataObj = arr.getJSONObject(0)
        Iterator<String> keys = dataObj.keys();
        names[i] = dataObj.getString(keys.next())
    }
    System.out.println(names);
}

I probably have some syntax issues in this answer, but the main idea is that you're trying to get a string while you're dealing with array of objects (each data index is an array of objects. It just so happens to be that there's only one object in each such array)

Avi
  • 21,182
  • 26
  • 82
  • 121
  • The `String` still comes out like this {"totalStars":500} – Richard Aug 14 '18 at 10:14
  • 1
    @kataroty - I don't remember the exact java syntax and objects, but I edited the answer. The idea is to get the array, get the iterator for the keys (which would only have one element) and get the value using the first key in the iterator. – Avi Aug 14 '18 at 10:17
0
public class DataObject
{
  private int code;

  public int getCode() { return this.code; }

  public void setCode(int code) { this.code = code; }

  private String message;

  public String getMessage() { return this.message; }

  public void setMessage(String message) { this.message = message; }

  private ArrayList<ArrayList<>> data;

  public ArrayList<ArrayList<>> getData() { return this.data; }

  public void setData(ArrayList<ArrayList<>> data) { this.data = data; }
}

Use this java object corresponding to your json for parsing from rest api. Use gson or jackson libraries.

Sumesh TG
  • 2,557
  • 2
  • 15
  • 29