0

I have Android app connected to MySQL database, everything works fine with the connection, but the data retrieved from database comes in JSON format, I use this class for connection:

public class CommunicatetoServer extends AsyncTask<String, Void, String> {


    @Override
    protected String doInBackground(String... params) {
        String response = "";

        String url = params[0];
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
            final int statusCode = getResponse.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                Log.w(getClass().getSimpleName(),
                        "Error " + statusCode + " for URL " + url);
                return null;
            }

            HttpEntity getResponseEntity = getResponse.getEntity();

            is = getResponseEntity.getContent();

            BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                response += s;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("IO", e.getMessage().toString());
            e.printStackTrace();

        }


        // return JSON String
        return response;

    }

    protected void onPostExecute(String response)
    {
        //onPostExecute
        Log.d("Server Response : ", response.toString());
        Toast.makeText(context, response.toString(), Toast.LENGTH_LONG).show();
    }

}

And I apply it like this:

private void GetComments() {
    new CommunicatetoServer().execute(SERVER_URL + "GetComments.php");
}

The method above is to retrieve all comments information from the database, and it comes in this way (the data is for test only):

[{"Uname":"test1","Id":"1","DateTime":"2015-03-04 00:00:00","comment":"Hello"},{"Uname":"test3","Id":"1","DateTime":"2015-02-04 10:23:42","comment":"asdffgsdg asdf"}]

So how can I convert it to java object?

Thank you.

user3504563
  • 39
  • 1
  • 2
  • 10
  • mmm I don't understand your problem, Can you tell me more details please? – Aspicas Mar 29 '15 at 23:11
  • @aspicas You see the last quote with the information user name and date etc. it is a JSON String, I want it to be in a form of java object where I can take each variable and print it alone not like a whole String. I hope you got my point. – user3504563 Mar 29 '15 at 23:15

3 Answers3

1

If you want to get an JSONObject, which can return childs etc., you could use the library JSON-Simple:

JSONObject obj = (JSONObject) new JSONParser().parse(jsonString);
dieckie
  • 74
  • 5
1

A JSON Object starts and ends with curly braces and JSON Array starts and ends with square brackets. What you have there is a JSON array.

If you want to print it out, you need to parse it. JSON is a key and value pair. So for example "Uname":"test3"Uname is the key and test3 is the value.

Look into HashMaps for JSON Arrays.

Here is an example I found from JSON Array iteration in Android/Java:

HashMap<String, String> applicationSettings = new HashMap<String,String>();
        for(int i = 0; i < settings.length(); i++){
            String value = settings.getJSONObject(i).getString("value");
            String name = settings.getJSONObject(i).getString("name");
            applicationSettings.put(name, value);
        }
Community
  • 1
  • 1
Adilp
  • 429
  • 1
  • 7
  • 21
0

Allow me to highly recommend you use a JSON -> Java Object mapper such as gson.

This will allow you to simply map between the serialized json representation of the data and you java object model.

First define your model class:

class Data {
  String Uname;
  Long Id;
  String DateTime; // can convert to a Date using a TypeAdapter
  String comment;
}

Then, use gson to parse your InputStream into your data:

is = getResponseEntity.getContent();

Gson gson = new Gson();
List<Data> data = gson.fromJson(new BufferedReader(is), new TypeToken<ArrayList<Data>>() {}.getType());

Now you can easily manipulate your data as you see fit using java objects.

Documentation for gson can be found here:

Gson: https://code.google.com/p/google-gson/

sddamico
  • 2,130
  • 16
  • 13