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?
You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK
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...
You can download a library from http://json.org (Json-lib or org.json) and use it to parse/generate the JSON
you just need to import this
im using two object because you can have an jsonObject within another
then i put the post json inside another like this
this is the method that i use to make a request
setting the connection
setting the outputstream
i use this to see in the logcat what i am sending
here the string is constructed
i use this log to see what its comming in the response
instancing a json with the String that contains the server response
This is the JsonParser class
Note: DefaultHttpClient is no longer supported by sdk 23, so it is advisable to use target sdk 21 with this code.
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