java : create nested json object from String - java

I want to create org.json.JSONObject from String.
the String is "user.phone.num : 00113". the result that i would like to have is org.json.JSONObject object with this format:
{
user:
{
phone: {num: 00113}
}
}
so is there any built in method to achieve this result. Thanks.

if every line of your json is splitted yo can try this code
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by ebi on 7/3/17.
*/
public class Main {
public static void main(String[] args) throws JSONException {
String str = "user.phone.num : 00113";
String json_str = str_to_json(str);
JSONObject jsonObject = new JSONObject(json_str);
System.out.println(jsonObject);
}
public static String str_to_json(String jsonByDot){
int valOffset = jsonByDot.indexOf(":");
String keys = jsonByDot.substring(0,valOffset).trim();
String val = jsonByDot.substring(valOffset+1).trim();
String keysArr[] = keys.split("\\.");
String output = "";
for(String key:keysArr){
output+="{"+key+":";
}
output+=val;
for (int i = 0 ;i<keysArr.length;i++){
output+="}";
}
return output;
}
}

Try using below -
JSONObject obj1 = new JSONObject();
obj1.put("birthdate", "01-01-2017");
obj1.put("age", new Integer(18));
JSONObject obj2 = new JSONObject();
obj2.put("name", "abc");
obj2.put("details", obj1);

Related

How can I create a new element/node and then add a new key and value to it?

I have the following code:
import org.json.JSONObject;
import org.json.XML;
public class Xml2Json {
public static void main(String[] args) {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
jsonObject.getJSONObject("users").append("marks",23); }
}
it produces the output shown below:
{"users":{"report":{"sub":"eng","score":30},"marks":[23],"user":{"name":"test1"}}}
But I need to add a new element newUser to users and the marks should be inside the newUser, just like:
{"users":{"report":{"sub":"eng","score":30},"newUser":{"marks":{23}},"user":{"name":"test1"}}}
Could anyone help me?
Instead of your code use below mentioned code:
public static void main(String[] args) throws JSONException {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
Map<String, int[]> marks = new HashMap<>();
marks.put("marks", new int[]{23});
jsonObject.getJSONObject("users").put("newUser", marks);
System.out.println(jsonObject);
}
where line jsonObject.getJSONObject("users").put("newUser", marks); will add new key(newUser) with corresponding mapping marks as Map object.
Without Map and HashMap:
public static void main(String[] args) throws JSONException {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
JSONObject marksJSONObject = new JSONObject();
marksJSONObject.put("marks",new int[]{23});
jsonObject.getJSONObject("users").put("newUser", marksJSONObject);
System.out.println(jsonObject);
}
OUTPUT:
{"users":{"newUser":{"marks":[23]},"report":{"sub":"eng","score":30},"user":{"name":"test1"}}}
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
JSONObject newUser = new JSONObject();
newUser.put("marks", 32);
jsonObject.put("newUser", newUser);

How to create array in json object

I am using something like this-
String Number1=to_1;
String Number2=to_2;
String[] arrayNumbers = new String[] {(char)34+Number1+(char)34,(char)34+Number2+(char)34};
System.out.println(Arrays.toString(arrayNumbers));
JSONObject jsonObj = new JSONObject();
jsonObj.put("to",Arrays.toString(arrayNumbers));
jsonObj.put("type",type);
jsonObj.put("callback",callbackUrl);
JSONArray array = new JSONArray();
JSONObject Array_item = new JSONObject();
jsonObj.put(type, array);
Array_item.put("caption",captionName);
array.add(Array_item);
System.out.println(jsonObj.toString());
Expected-
{
"to":["91890xx", "91890xx"],
"type": "document", "document" : {"caption" : "doc"},
"callback":"{{callback}}"
}
Actual- {"document":[{"caption":"hello"}],"callback":"{{callback}}","to":"[\"91890xxx\", \"91890xx\"]","type":"document"}
I don't know any more logic to remove the out double quotes of to number where as its considering that to a string where as both the numbers should be array format as mentioned in Expected.
First, I show you the correct codes:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
/**
* <pre>
* {
* "to":["91890xx", "91890xx"],
* "type": "document",
* "document" : {"caption" : "doc"},
* "callback":"{{callback}}"
* }
* </pre>
*
* #param args
* #throws JSONException
*/
public static void main(String[] args) throws JSONException {
String number1 = "91890";
String number2 = "91890";
String[] numbers = new String[]{number1, number2};
JSONArray toNode = new JSONArray();
for (String number : numbers) {
toNode.put(number);
}
JSONObject jsonObj = new JSONObject();
jsonObj.put("to", toNode);
jsonObj.put("type", "document");
jsonObj.put("document", new JSONObject().put("caption", "doc"));
jsonObj.put("callback", "{{callback}}");
System.out.println(jsonObj.toString());
}
}
Result:
{"document":{"caption":"doc"},"callback":"{{callback}}","to":["91890","91890"],"type":"document"}
If you want create a josn array node, you show use JSONArray, and use JSONArray#put(*) method to add elements.
Put string into JSONArray or JSONObject, you don't need wrap the string with quote("). Besides, you should write \" instead of (char) 34 which is a little obscure in Java.
The following case is used to reply comments.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.util.*;
public class Test1 {
public static void main(String[] args) throws JSONException {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", new Date());
map.put("key3", 1);
map.put("key4", null);
map.put("key5", Collections.singletonMap("key5-key1", "value"));
map.put("key6", Arrays.asList(1, 2, 3, 4));
map.put("key7", BigDecimal.TEN);
map.put("key8", new String[]{"a", "b", "c"});
map.put("key9", TestEnum.A);
map.put("key10", new TestEnum[]{TestEnum.A, TestEnum.B, TestEnum.C});
Object json = buildJsonObj(map);
System.out.println(json);
}
private static Object buildJsonObj(Object source) throws JSONException {
if (source == null) {
return null;
}
if (isSimpleValueType(source.getClass())) {
return source;
}
if (source instanceof Map) {
Map<Object, Object> map = (Map<Object, Object>) source;
JSONObject jsonObject = new JSONObject();
for (Map.Entry<Object, Object> entry : map.entrySet()) {
Object key = entry.getKey();
if (!(key instanceof String)) {
throw new IllegalArgumentException("key must be string.");
}
jsonObject.put((String) key, buildJsonObj(entry.getValue()));
}
return jsonObject;
}
if (source instanceof Iterable) {
Iterable<Object> iterable = (Iterable<Object>) source;
JSONArray jsonArray = new JSONArray();
for (Object value : iterable) {
jsonArray.put(buildJsonObj(value));
}
return jsonArray;
}
if (source.getClass().isArray()) {
Object[] array = (Object[]) source;
JSONArray jsonArray = new JSONArray();
for (Object value : array) {
jsonArray.put(buildJsonObj(value));
}
return jsonArray;
}
throw new IllegalArgumentException("Unsupported type: " + source + ".");
}
private static boolean isSimpleValueType(Class<?> clazz) {
return (Enum.class.isAssignableFrom(clazz) ||
CharSequence.class.isAssignableFrom(clazz) ||
Number.class.isAssignableFrom(clazz) ||
Date.class.isAssignableFrom(clazz) ||
URI.class == clazz || URL.class == clazz ||
Locale.class == clazz);
}
public enum TestEnum {
A, B, C
}
}
Result:
{"key1":"value1","key2":"Thu Mar 14 20:20:49 CST 2019","key5":{"key5-key1":"value"},"key6":[1,2,3,4],"key3":1,"key9":"A","key7":10,"key8":["a","b","c"],"key10":["A","B","C"]}
Replace line
jsonObj.put("to",Arrays.toString(arrayNumbers));
to
jsonObj.put("to", Arrays.asList(arrayNumbers));
Your value is String of 'to',so can you please convert string to json after that you can convert json to array.
Replace
jsonObj.put("to",Arrays.toString(arrayNumbers));
With
jsonObj.put("to",arrayNumbers);
let a = {"document":[{"caption":"hello"}],"callback":"{{callback}}","to":"[\"91890xxx\", \"91890xx\"]","type":"document"};
a = JSON.parse(JSON.stringify(a));
let b = JSON.parse(a.to);
a.to = b;
console.log(a);
This is the exact structure of you required json.
{
"to": ["91890xx", "91890xx"],
"type": "document",
"document": {
"caption": "doc"
},
"callback": "{{callback}}"
}
To Remove the double quotes, please use replace function as shown below
String Number1="[\"91890xxx\", \"91890xx\"]";
Number1.replace("\\/", "");
System.out.println("Excepted output:"+Number1);
output:
Excepted output:["91890xxx", "91890xx"]

Parsing google json with java

I need to parse JSON:
{
"Store":"GooglePlay",
"TransactionID":"here_is_google_transaction_id",
"Payload":"{"json":"{"packageName":"com.myapp.mypackage","productId":"com.myapp.mypackage.myproductid","purchaseTime":1489056122448,"purchaseState":0,"purchaseToken":"here_is_my_purchase_token"}",
"signature":"here_is_signature_g=="}"}
I need to get "Payload" attributes like "packageName", "productId" and so on.
How can i do that with java?
I tried to use JsonParser:
private static final void readJson(String json) {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
JsonObject rootObject = jsonElement.getAsJsonObject(); //get whole json object
String store = rootObject.get("Store").getAsString(); //get store attribute value
JsonObject childObject = rootObject.getAsJsonObject("Payload"); //get payload json object from root object
String packageName = childObject.get("packageName").getAsString();
System.out.println(store + " " + packageName);
}
But it throws an error when i'm trying to get the "Payload" object content:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
at com.google.gson.JsonObject.getAsJsonObject(JsonObject.java:191)
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo {
public static void main(String[] args){
JSONParser parser = new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s = "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s = "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
A very simple representation of JSONParser.
And its output
The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]
Ref: https://www.tutorialspoint.com/json/json_java_example.htm

Iterating through json array with appended json string in android after json as response from url using volley

Hi i am trying to iterate through a json string that looks like this:
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":
{
"25":
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
"26":
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
"27":
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
}
}
here is a better view of the json string:
I am iterating through the vendor array of this json string using this code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
}
but I dont know how to get data from the "products" object please help me how do i set my json objects to iterate through "products"
when i try to change the format of the array so that both products and vendor are a separate json array i still get the above json format..
this is what i am doing
$resp_array['vendor'] = $info;
$resp_array['products'] = $vendorProductsInfo;
$resp_array = json_encode($resp_array);
print_r($resp_array);
please help me with this
MODIFIED QUESTION:
I have modified my web response like this:
[{"entity_id":24,"product_name":"Burger","product_image_url":"\/b\/u\/burger_large.jpg","price":"234.0000","category_id":59},{"entity_id":27,"product_name":"Chicken Biryani","product_image_url":"\/b\/i\/biryani.jpg","price":"500.0000","category_id":59},{"entity_id":31,"product_name":"Pizza","product_image_url":"\/p\/i\/pizza_png7143_1.png","price":"125.0000","category_id":59}]
and the code:
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
JSONObject jsono1 = new JSONObject(response);
JSONArray childrenProducts = jsono1.getJSONArray("products");
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.print(jsonData.getString("name") + "<----dd");
}
but still the products part is not working... please help
Here is the working solution: Using GOOGLE GSON (Open source jar)
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonToJava {
public static void main(String[] args) throws IOException {
try{
String json = "<YOUR_JSON>";
Gson gson = new GsonBuilder().create();
VendorInfo vInfo = gson.fromJson(json, VendorInfo.class);
System.out.println(vInfo.getVendorName());
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Create classes for Vendor and Product
public class Vendor {
public String vendor_name;
public String vendor_description;
public String vendor_slug;
public String vendor_logo;
public String contact_number;
public String getName() {
return vendor_name;
}
}
public class Product {
public String name;
public long price;
public String image;
public String getName() {
return name;
}
}
VendorInfo is the JSON object form:
import java.util.Map;
public class VendorInfo {
public Vendor[] vendor;
public Map<Integer, Product> products;
public String getVendorName() {
return vendor[0].getName();
}
public Product getProduct() {
System.out.println(products.size());
return products.get(25);
}
}
You can add your getters for Vendor, Product and VendorInfo. You are done! You will get all the data.
Output of JsonToJava:
Tapan Moharana
To get your products data , you need to use Iterator
JSONObject jProducts = jsonObject
.optJSONObject("products");
try {
if (jProducts
.length() > 0) {
Iterator<String> p_keys = jProducts
.keys();
while (p_keys
.hasNext()) {
String keyProduct = p_keys
.next();
JSONObject jP = jProducts
.optJSONObject(keyProduct);
if (jP != null) {
Log.e("Products",
jP.toString());
}
}
}
} catch (Exception e) { // TODO:
// handle
// exception
}
you can try with this
JSONObject jsono = null;
try {
jsono = new JSONObject(response);
JSONObject productObject = jsono.getJSONObject("products");
Iterator<String> keys = productObject.keys();
while (keys.hasNext())
{
// get the key
String key = keys.next();
// get the value
JSONObject value = productObject.getJSONObject(key);
//get seprate objects
String name = value.getString("name");
String image = value.getString("image");
Log.i(TAG,name+"-"+image);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Try this :
JSONObject productObject = jsono.getJSONObject("products");
JSONObject json_25 = productObject getJSONObject("25");
String name_25= json_25.getString("name");
String price_25= json_25.getString("price");
String image_25= json_25.getString("image");
JSONObject json_26 = productObject getJSONObject("26");
String name_26= json_26.getString("name");
String price_26= json_26.getString("price");
String image_26= json_26.getString("image");
JSONObject json_27 = productObject getJSONObject("27");
String name_27= json_27.getString("name");
String price_27= json_27.getString("price");
String image_27= json_27.getString("image");

How to read json file into java with simple JSON library

I want to read this JSON file with java using json simple library.
My JSON file looks like this:
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
This is the java code I wrote to read this file:
package javaapplication1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JavaApplication1 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\file.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
But I get the following exception:
Exception in thread "main" java.lang.ClassCastException:
org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)
Can somebody tell me what I am doing wrong? The whole file is a array and there are objects and another array (cars) in the whole array of the file. But i dont know how I can parse the whole array into a java array. I hope somebody can help me with a code line which I am missing in my code.
Thanks
The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.
As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...
JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) person.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
For reference, see "Example 1" on the json-simple decoding example page.
You can use jackson library and simply use these 3 lines to convert your json file to Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
Add Jackson databind:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr2</version>
</dependency>
Create DTO class with related fields and read JSON file:
ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
Reading from JsonFile
public static ArrayList<Employee> readFromJsonFile(String fileName){
ArrayList<Employee> result = new ArrayList<Employee>();
try{
String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(text);
JSONArray arr = obj.getJSONArray("employees");
for(int i = 0; i < arr.length(); i++){
String name = arr.getJSONObject(i).getString("name");
short salary = Short.parseShort(arr.getJSONObject(i).getString("salary"));
String position = arr.getJSONObject(i).getString("position");
byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company"));
if (position.compareToIgnoreCase("manager") == 0){
result.add(new Manager(name, salary, position, years_in_company));
}
else{
result.add(new OrdinaryEmployee(name, salary, position, years_in_company));
}
}
}
catch(Exception ex){
System.out.println(ex.toString());
}
return result;
}
Use google-simple library.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Please find the sample code below:
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
//Use JSONObject for simple JSON and JSONArray for array of JSON.
JSONObject data = (JSONObject) parser.parse(
new FileReader("/resources/config.json"));//path to the JSON file.
String json = data.toJSONString();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
Use JSONObject for simple JSON like {"id":"1","name":"ankur"} and JSONArray for array of JSON like [{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}].
Might be of help for someone else facing the same issue.You can load the file as string and then can convert the string to jsonobject to access the values.
import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);
Gson can be used here:
public Object getObjectFromJsonFile(String jsonData, Class classObject) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(jsonData);
return gson.fromJson(object, classObject);
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Delete_01 {
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException {
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
"delete_01.json"));
for (Object o : jsonArray) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String strCity = (String) person.get("city");
System.out.println("City::::" + strCity);
JSONArray arrays = (JSONArray) person.get("cars");
for (Object object : arrays) {
System.out.println("cars::::" + object);
}
String strJob = (String) person.get("job");
System.out.println("Job::::" + strJob);
System.out.println();
}
}
}
Following is the working solution to your problem statement as,
File file = new File("json-file.json");
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(file));
JSONArray jsonArray = new JSONArray(obj.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.get("name"));
System.out.println(jsonObject.get("city"));
System.out.println(jsonObject.get("job"));
jsonObject.getJSONArray("cars").forEach(System.out::println);
}
Hope this example helps too
I have done java coding in a similar way for the below json array example as follows :
following is the json data format : stored as "EMPJSONDATA.json"
[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},
{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},
{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}
{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]
public class Jsonminiproject {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
for (Object o : a)
{
JSONObject employee = (JSONObject) o;
Long no = (Long) employee.get("EMPNO");
System.out.println("Employee Number : " + no);
String st = (String) employee.get("EMP_NAME");
System.out.println("Employee Name : " + st);
String dob = (String) employee.get("DOB");
System.out.println("Employee DOB : " + dob);
String doj = (String) employee.get("DOJ");
System.out.println("Employee DOJ : " + doj);
String role = (String) employee.get("ROLE");
System.out.println("Employee Role : " + role);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.json;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJSONFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json"));
JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) array.get(0);
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This issue occurs when you are importing the org. json library for JSONObject class. Instead you need to import org.json.simple library.
private static final JsonParser JSON_PARSER = new JsonParser();
private static final String FILE_PATH = "configuration/data.json";
private JsonObject readJsonDataFromFile() {
try {
File indexFile = new File(FILE_PATH);
String fileData = Files.toString(indexFile, Charsets.UTF_8);
return (JsonObject) JSON_PARSER.parse(fileData);
} catch (IOException | JsonParseException e) {
String error = String.format("Error while reading file %s", FILE_PATH);
log.error(error);
throw new RuntimeException(error, e);
}
}
public class JsonParser {
public static JSONObject parse(String file) {
InputStream is = JsonParser.class.getClassLoader().getResourceAsStream(file);
assert is != null;
return new JSONObject(new JSONTokener(is));
}
}
// Read Json
JSONObject deviceObj = new JSONObject(JsonParser.parse("Your Json filename").getJSONObject(deviceID).toString());
Perform logic to iterate
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonParserTest {
public static void main(String[] args) throws IOException {
String data = new String(Files.readAllBytes(Paths.get("C:/json.txt")));
JsonElement jsonElement = JsonParser.parseString(data);
JsonObject json = jsonElement.getAsJsonObject();
System.out.println(json.get("userId"));
System.out.println(json.get("id"));
System.out.println(json.get("title"));
System.out.println(json.get("completed"));
}
}
Use the below repositay from GSON.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Sample Json
{
"per_page": 3,
"total": 12,
"data": [{
"last_name": "Bluth",
"id": 1,
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
"first_name": "George"
},
{
"last_name": "Weaver",
"id": 2,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
"first_name": "Janet"
},
{
"last_name": "Wong",
"id": 3,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
"first_name": "Emma"
}
],
"page": 1,
"total_pages": 4
}
First If statement will convert the single data from the body
Second if statement will differentiate the JsonArray object
public static String getvalueJpath(JSONObject responseJson, String Jpath ) {
Object obj = responseJson;
for(String s : Jpath.split("/"))
if (s.isEmpty())
if(!(s.contains("[") || s.contains("]")))
obj = ((JSONObject) obj).get(s);
else
if(s.contains("[") || s.contains("]"))
obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", "")));
return obj.toString();
}
}
Solution using Jackson library. Sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
your json file look like this
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
JSONObject jsonObject = (JSONObject)obj;
String name = (String)jsonObject.get("Name");
String course = (String)jsonObject.get("Course");
JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
System.out.println("Name: " + name);
System.out.println("Course: " + course);
System.out.println("Subjects:");
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
the output is
Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML
took it from here
try {
Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));
// JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) obj;
JSONObject orchestration = (JSONObject) jsonObject.get("orchestration");
JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
JSONObject schedule = (JSONObject) trigger.get("schedule");
JSONObject trade = (JSONObject) schedule.get("trade-query");
// loop array
JSONArray filter = (JSONArray) trade.get("filter");
for (Object o : filter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String operand = (String) person.get("operand");
System.out.println("City::::" + operand);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
JSONArray parameter = (JSONArray) trade.get("parameter");
for (Object o : parameter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
try {
//Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));
// create object mapper instance
ObjectMapper mapper = new ObjectMapper();
// convert JSON string to Book object
Object obj = mapper.readValue(Paths.get("C:/Local Disk/file.json").toFile(), Object.class);
// print book
System.out.println(obj);
String jsonInString = new Gson().toJson(obj);
JSONObject mJSONObject = new JSONObject(jsonInString);
System.out.println("value::::" + mJSONObject);
JSONObject orchestration = (JSONObject) mJSONObject.get("orchestration");
JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
JSONObject schedule = (JSONObject) trigger.get("schedule");
JSONObject trade = (JSONObject) schedule.get("trade-query");
// loop array
JSONArray filter = (JSONArray) trade.get("filter");
for (Object o : filter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String operand = (String) person.get("operand");
System.out.println("City::::" + operand);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
JSONArray parameter = (JSONArray) trade.get("parameter");
for (Object o : parameter) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String value = (String) person.get("value");
System.out.println("value::::" + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use readAllBytes.
return String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);

Categories

Resources