1

I got a problem with a JSONObject. I'm receiving data from my website to an android app, the JSONParser returns a JSONObject:

public JSONObject makeHttpRequest(String url, String method, HashMap<String, String> params) {

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    if (method.equals("POST")) {
        // NOT IMPORTANT, WORKS FINE
    } else if(method.equals("GET")) {

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setConnectTimeout(15000);
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

    }

    conn.disconnect();
    return jObj;
}

Here's my getAsync class:

class GetAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = my_url;

    @Override
    protected JSONObject doInBackground(String... args) {

        JSONObject json = null;

        try {
            HashMap<String, String> params = new HashMap<>();
            Log.d("request", "startingGET");
            json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);

            if (json != null) {
                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return json;
    }

    protected void onPostExecute(JSONObject json) {
         // DUNNO WHAT TO WRITE HERE
    }
}

JSONParser returns:

 D/JSON Parser: result: {"success":1,"message":"Scores downloaded properly","scores":[{"place":"1","nick":"testnick","score":"1149","date":"2016-08-13 14:00:07"},{"place":"2","nick":"testnick","score":"741","date":"2016-08-13 11:35:28"}, [...]

But I want the result as a String[][], HashMap, ArrayList or whatever else that could be useful to show the result as a ranking later. To get rid of the "success" and "message" arrays I can use one of the following lines (I'm not using both at the same time) in the doInBackround or onPostExecute:

json = json.optJSONObject("scores");
JSONArray jsonArray = json.optJSONArray("scores");

And here's where I stopped. Been searching the whole day how to convert it into one of the previously mentioned types. I've even tried iterating a String stream char by char... and there always been a problem. I have no idea what else to try, help me, please.

6
  • 1
    Just use JSONArray jsonArray = json.optJSONArray("scores"); remove json = json.optJSONObject("scores"); line Commented Aug 13, 2016 at 13:50
  • I said I'm using only one of these lines, not both at the same time. Commented Aug 13, 2016 at 13:53
  • JSONArray jsonArray = jsonObj.getJSONArray("scores"); Commented Aug 13, 2016 at 14:07
  • @ravthiru also tried this, also returns an unhandled JSON Exception Commented Aug 13, 2016 at 14:10
  • You should really look into Retrofit Commented Aug 13, 2016 at 14:30

2 Answers 2

3

You could create a simple POJO:

public class Ranking {

    private int place;
    private String nick;
    private int score;
    private String date;

    public int getPlace() {
        return place;
    }

    public void setPlace(int place) {
        this.place = place;
    }

    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public int getScore() {
        return score;
    }

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

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

And then do something like this to get a List of Rankings:

List<Ranking> rankingList = new ArrayList<>();

try {
    JSONArray array = json.optJSONArray("scores");

    for (int i = 0; i < array.length(); i++) {
        JSONObject rankingObject = array.getJSONObject(i);

        Ranking ranking = new Ranking();
        ranking.setPlace(rankingObject.getInt("place"));
        ranking.setNick(rankingObject.getString("nick"));
        ranking.setScore(rankingObject.getInt("score"));
        ranking.setDate(rankingObject.getString("date"));

        rankingList.add(ranking);
    }
} catch (JSONException j) {
    j.printStackTrace();
}

// do whatever you want with rankingList

Or use Gson to make the parsing simplier:

String rankingsJson = json.optJSONArray("scores").toString();

List<Ranking> rankingList = new Gson().fromJson(rankingsJson,
            new TypeToken<List<Ranking>>(){}.getType());
Sign up to request clarification or add additional context in comments.

Comments

0
protected void onPostExecute(JSONObject json) {
     // DUNNO WHAT TO WRITE HERE --> DO THE FOLLOWING :

        JSONArray jsonArray = json.optJSONArray("scores");

        HashMap<String, String>[] resultMap = new HashMap[jsonArray.length()];
        for(int i=0; i<jsonArray.length(); i++){
            String place = jsonArray.getJSONObject(i).getString("place");
            String nick = jsonArray.getJSONObject(i).getString("nick");
            String score = jsonArray.getJSONObject(i).getString("score");
            String date = jsonArray.getJSONObject(i).getString("date");

            resultMap[i] = new HashMap<>();
            resultMap[i].put("place", place);
            resultMap[i].put("nick", nick);
            resultMap[i].put("score", score);
            resultMap[i].put("date", date);

        }
}

Explanation: jsonArray contains the following data:

[{"date":"2016-08-13 14:00:07","score":"1149","nick":"testnick","place":"1"},{"date":"2016-08-13 11:35:28","score":"741","nick":"testnick","place":"2"}]

Note that its length is two in this case. To access this array you should iterate on jsonArray and get each row/value using jsonArray.getJSONObject(i) Then each row contains the four items: place, nick, score, date.

I used HashMap[] to store each row in a map. And the map array will store the group of rows.

1 Comment

there's also jsonArray.getJSONObject(i) underlined - unhandled JSONException, I was already trying sth similar; I already got a correct answer, thanks for your interest anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.