Showing posts with label json from string. Show all posts
Showing posts with label json from string. Show all posts

Saturday, 16 March 2019

Create JSONArray from JSON String


By passing JSON String to the JSONArray constructor, you can construct JSONArray from the string.

Example
JSONArray jsonArray = new JSONArray(jsonString);

App.java
package com.sample;

import org.json.JSONArray;

public class App {

 public static void main(String args[]) {
  String jsonString = "[{\"organization\":\"ABC Corporation\",\"name\":\"Krishna\",\"id\":1},{\"organization\":\"XYZ Corporation\",\"name\":\"Rama\",\"id\":2},{\"organization\":\"TUV Corporation\",\"name\":\"Chamu\",\"id\":3}]\n";
  JSONArray jsonArray = new JSONArray(jsonString);

  System.out.println(jsonArray.get(0));
  System.out.println(jsonArray.get(1));
  System.out.println(jsonArray.get(2));

 }
}

Output
{"organization":"ABC Corporation","name":"Krishna","id":1}
{"organization":"XYZ Corporation","name":"Rama","id":2}
{"organization":"TUV Corporation","name":"Chamu","id":3}



Previous                                                 Next                                                 Home

JsonObject: Construct a json object from string


By passing json string to JSONObject constructor, you can create a json object.

Syntax
JSONObject jsonObject = new JSONObject(jsonString);

Example
String jsonString = "{\"organization\":\"ABC Corportion\",\"name\":\"Krishna\",\"id\":123}";

App.java
package com.sample;

import org.json.JSONObject;

public class App {

 public static void main(String args[]) {
  String jsonString = "{\"organization\":\"ABC Corportion\",\"name\":\"Krishna\",\"id\":123}";

  JSONObject jsonObject = new JSONObject(jsonString);

  System.out.println("name : " + jsonObject.get("name"));
  System.out.println("id : " + jsonObject.get("id"));
  System.out.println("organization : " + jsonObject.get("organization"));

 }
}

Output
name : Krishna
id : 123
organization : ABC Corportion



Previous                                                 Next                                                 Home