Tutorial by Examples

Consider the following JSON string: { "title": "test", "content": "Hello World!!!", "year": 2016, "names" : [ "Hannah", "David", "Steve" ] } This JSON object can...
Create the JSONObject using the empty constructor and add fields using the put() method, which is overloaded so that it can be used with different types: try { // Create a new instance of a JSONObject final JSONObject object = new JSONObject(); // With put you can add a name/va...
// Create a new instance of a JSONArray JSONArray array = new JSONArray(); // With put() you can add a value to the array. array.put("ASDF"); array.put("QWERTY"); // Create a new instance of a JSONObject JSONObject obj = new JSONObject(); try { // Add the JSONAr...
If you need to produce a JSON string with a value of null like this: { "name":null } Then you have to use the special constant JSONObject.NULL. Functioning example: jsonObject.put("name", JSONObject.NULL);
{ "some_string": null, "ather_string": "something" } If we will use this way: JSONObject json = new JSONObject(jsonStr); String someString = json.optString("some_string"); We will have output: someString = "null"; So we need to...
JsonReader reads a JSON encoded value as a stream of tokens. public List<Message> readJsonStream(InputStream in) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { return readMessagesArray(reader); } finall...
To produce nested JSON object, you need to simply add one JSON object to another: JSONObject mainObject = new JSONObject(); // Host object JSONObject requestObject = new JSONObject(); // Included object try { requestObject.put("lastname", lastname); reques...
This is an example for how to handle dynamic key for response. Here A and B are dynamic keys it can be anything Response { "response": [ { "A": [ { "name": "Tango" }, { "name": "P...
Sometimes it's useful to check if a field is present or absent on your JSON to avoid some JSONException on your code. To achieve that, use the JSONObject#has(String) or the method, like on the following example: Sample JSON { "name":"James" } Java code String jsonStr...
sample json to update { "student":{"name":"Rahul", "lastname":"sharma"}, "marks":{"maths":"88"} } To update the elements value in the json we need to assign the value and update. try { // Create a new in...

Page 1 of 1