How can I create a JSON with this format in Android: Since the API that I will be passing will parse JsonArray then the object. Or would it be okay if just to pass a json object? Since I will just have to insert 1 transaction per service call.
{
"student": [
{
"id": 1,
"name": "John Doe",
"year": "1st",
"curriculum": "Arts",
"birthday": 3/3/1995
},
{
"id": 2,
"name": "Michael West",
"year": "2nd",
"curriculum": "Economic",
"birthday": 4/4/1994
}
]
}
What I know is only the JSONObject. Like this one.
JSONObject obj = new JSONObject();
try {
obj.put("id", "3");
obj.put("name", "NAME OF STUDENT");
obj.put("year", "3rd");
obj.put("curriculum", "Arts");
obj.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any ideas. Thanks
Use the following code:
You can create a a method and pass paramters to it and get the json as a response.
I hope this will help you.
Here's a simpler (but not so short) version which doesn't require try-catch:
If you want to add a jsonObject into a field, you can do this way:
Unfortunately it needs a try-catch because of the put() method.
IF you want to avoid try-catch again (not very recommended, but it's ok if you can guarantee well formated json strings), you might do this way:
You can do the same about JsonArrays and so on.
Cheers.