kuznikowski
kuznikowski

Reputation: 563

Problems converting JSONObject/JSONArray to String array

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.

Upvotes: 1

Views: 794

Answers (2)

earthw0rmjim
earthw0rmjim

Reputation: 19427

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

Upvotes: 3

Abdulhamid Dhaiban
Abdulhamid Dhaiban

Reputation: 646

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.

Upvotes: 0

Related Questions