kuznikowski kuznikowski - 3 months ago 7
Java Question

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.

Answer

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

    @Override
    public String toString() {
        return place + nick + score + 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());
Comments