I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:
[
{
"user":{"id":"1","username":"user1"},
"item_name":"item1",
"custom_field":"custom1"
},
{
"user":{"id":"2","username":"user2"},
"item_name":"item2",
"custom_field":"custom2"
},
{
"user":{"id":"3","username":"user3"},
"item_name":"item3",
"custom_field":"custom3"
}
]
If you want to use Gson, then first you declare classes for holding each element and sub elements:
Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:
Then you simply access the elements of
data
.The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item_name" etc.
You could try JSON Simple
http://code.google.com/p/json-simple/
Example:
Just be careful to check for nulls/be careful with casting and such.
If your trying to serialize/deserialize json in Java I would recommend using Jackson. http://jackson.codehaus.org/
Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON.
Jackson provides annotations that can be attached to your class which make deserialization pretty simple.