139

I would like to send messages in the form of JSON objects to a server and parse the JSON response from the server.

Example of JSON object

{
  "post": {
    "username": "John Doe",
    "message": "test message",
    "image": "image url",
    "time":  "current time"
  }
}

I am trying to parse the JSON manually by going attribute by attribute. Is there any library/utility I can use to make this process easier?

Primal Pappachan
  • 25,857
  • 22
  • 67
  • 84
  • 2
    That URL is no longer available... could you update it? – Cipi Oct 05 '11 at 10:44
  • 1
    Here is a detailed example: [Android – JSON Parsing example](http://www.technotalkative.com/?p=1413) – Paresh Mayani Nov 18 '11 at 07:24
  • 1
    @ Paresh Mayani & @[primpap](http://stackoverflow.com/users/323404/primpap) .. I know that We can populate data from the server using JSON recieved from server using get method, I am comfortable with it .... but if we use post method to send the data to server, do we send the data as JSON again, I am refering to Quotation of primpap question " I would like to send messages in the form of JSON objects to a Django Server " ..... I am using Mysql on server .... or I send JSON object ? ... can you clarify this info to me .... or any links that help me understand the concept will be helpful, Thanks – Devrath Aug 27 '13 at 17:31

11 Answers11

118

I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:

So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)

EDIT 19-MAR-2014:

Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well. So it just might be good choice, especially for smaller apps.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 10
    +1 for GSON. We have especially used GSON's streaming support http://sites.google.com/site/gson/streaming in our Android apps. – Andre Steingress Apr 20 '11 at 20:19
  • FWIW, Jackson also has streaming API: http://wiki.fasterxml.com/JacksonStreamingApi – StaxMan Apr 21 '11 at 17:34
  • 2
    Also +1 for GSON streaming. Implemented Jackson streaming at first but though functional in debug version, ProGuard generated tons of errors and release version causes crashes which are hard to trackdown. I am sure this is no Jackson related issue, but it made me switch to GSON which worked fine and only required additional 14kB for just streaming. – sven Jun 17 '11 at 10:37
  • And for stupid unpredicatble json mixing string and lists ex: ["toto", "tata", ["monty", ["tor", "python"]]]? (kind of data structure requiring recursive functions to consume it) – christophe31 Jul 28 '14 at 14:00
85

You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK

Valentin Golev
  • 9,965
  • 10
  • 60
  • 84
31

GSON is easiest to use and the way to go if the data have a definite structure.

Download gson.

Add it to the referenced libraries.

package com.tut.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleJson extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String jString = "{\"username\": \"tom\", \"message\": \"roger that\"}  ";


        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        Post pst;

        try {
            pst = gson.fromJson(jString,  Post.class);

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

Code for Post class

package com.tut.JSON;

public class Post {

    String message;
    String time;
    String username;
    Bitmap icon;
}
Primal Pappachan
  • 25,857
  • 22
  • 67
  • 84
  • 4
    For what it's worth, code can be simplified: that JSONObject conversion is unnecessary. And setters and getters are optional for GSon; can be added if one wants, but not strictly necessary. – StaxMan Sep 15 '10 at 00:04
  • 4
    Just to clarify StaxMan's comment. Your example is taking jString, converting it to a JSONObject, then converting it back to a String for the gson to read. Simply use pst = gson.fromJson(jString, Post.class). I believe this will also get rid of the need for try-catch. And as StaxMan also points out, the setters & getters in the Post.class add no value. It would be helpful to others to correct your example. – Matt Nov 27 '11 at 22:06
  • I removed the double conversion part from the answer – whlk May 24 '12 at 14:55
4

This is the JsonParser class

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

Note: DefaultHttpClient is no longer supported by sdk 23, so it is advisable to use target sdk 21 with this code.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
3

There's not really anything to JSON. Curly brackets are for "objects" (associative arrays) and square brackets are for arrays without keys (numerically indexed). As far as working with it in Android, there are ready made classes for that included in the sdk (no download required).

Check out these classes: http://developer.android.com/reference/org/json/package-summary.html

Rich
  • 36,270
  • 31
  • 115
  • 154
2

Other answers have noted Jackson and GSON - the popular add-on JSON libraries for Android, and json.org, the bare-bones JSON package that is included in Android.

But I think it is also worth noting that Android now has its own full featured JSON API.

This was added in Honeycomb: API level 11.

This comprises
- android.util.JsonReader: docs, and source
- android.util.JsonWriter: docs, and source

I will also add one additional consideration that pushes me back towards Jackson and GSON: I have found it useful to use 3rd party libraries rather then android.* packages because then the code I write can be shared between client and server. This is particularly relevant for something like JSON, where you might want to serialize data to JSON on one end for sending to the other end. For use cases like that, if you use Java on both ends it helps to avoid introducing android.* dependencies.

Or I guess one could grab the relevant android.* source code and add it to your server project, but I haven't tried that...

Tom
  • 17,103
  • 8
  • 67
  • 75
1

You can download a library from http://json.org (Json-lib or org.json) and use it to parse/generate the JSON

gvaish
  • 9,374
  • 3
  • 38
  • 43
1

you just need to import this

   import org.json.JSONObject;


  constructing the String that you want to send

 JSONObject param=new JSONObject();
 JSONObject post=new JSONObject();

im using two object because you can have an jsonObject within another

post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time":  "present time");

then i put the post json inside another like this

  param.put("post",post);

this is the method that i use to make a request

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

setting the connection

        urlConnection = new URL("your url");
        connection = (HttpURLConnection) urlConnection.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(60000);
        connection.connect();

setting the outputstream

        dataOutputStream = new DataOutputStream(connection.getOutputStream());

i use this to see in the logcat what i am sending

        Log.d("OUTPUT STREAM  " ,param);
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        InputStream in = new BufferedInputStream(connection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;

here the string is constructed

        while ((line = reader.readLine()) != null)
        {
            result.append(line);
        }

i use this log to see what its comming in the response

         Log.d("INPUTSTREAM: ",result.toString());

instancing a json with the String that contains the server response

        jResponse=new JSONObject(result.toString());

    }
    catch (IOException e) {
        e.printStackTrace();
        return jResponse=null;
    } catch (JSONException e)
    {
        e.printStackTrace();
        return jResponse=null;
    }
    connection.disconnect();
    return jResponse;
}
  • thank for your time in advance. I use your code for sending base64 encoded string to django server but when i click the button to send in to server, APP goes crash. Could you help me how to tackle this? – Noman marwat Jul 21 '19 at 11:29
0

if your are looking for fast json parsing in android than i suggest you a tool which is freely available.

JSON Class Creator tool

It's free to use and it's create your all json parsing class within a one-two seconds.. :D

Community
  • 1
  • 1
sachin
  • 29
  • 4
0

Although there are already excellent answers are provided by users such as encouraging use of GSON etc. I would like to suggest use of org.json. It includes most of GSON functionalities. It also allows you to pass json string as an argument to it's JSONObject and it will take care of rest e.g:

JSONObject json = new JSONObject("some random json string");

This functionality make it my personal favorite.

Moosa
  • 79
  • 1
  • 2
  • 12
0

There are different open source libraries, which you can use for parsing json.

org.json :- If you want to read or write json then you can use this library. First create JsonObject :-

JSONObject jsonObj = new JSONObject(<jsonStr>);

Now, use this object to get your values :-

String id = jsonObj.getString("id");

You can see complete example here

Jackson databind :- If you want to bind and parse your json to particular POJO class, then you can use jackson-databind library, this will bind your json to POJO class :-

ObjectMapper mapper = new ObjectMapper();
post= mapper.readValue(json, Post.class);

You can see complete example here

Akash
  • 39
  • 2