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);
Related
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
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");
I'm trying to read JSON file in Java (I'm starting with JSON).
The JSON file:
[
{
"idProducto":1,
"Nombre":"Coca Cola",
"Precio":0.9,
"Cantidad":19
},
{
"idProducto":2,
"Nombre":"Coca Cola Zero",
"Precio":0.6,
"Cantidad":19
},
[....]
]
I tried the following:
ArrayList<Dispensador> Productos = new ArrayList<Dispensador>();
FileReader reader = new FileReader(new File("productos.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
Long idProducto = (Long) object.get("idProducto");
JSONArray nombres = object.getJSONArray("idProducto");
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
String nombre = (String) object.get("Nombre");
Double precio = (Double) object.get("Precio");
BigDecimal precioB = new BigDecimal(precio);
Long cantidad = (Long) object.get("Cantidad");
int cantidadB = toIntExact(cantidad);
System.out.println(nombre);
Productos.add(new Dispensador(nombre, precioB, cantidadB));
}
But enters into loop. Also I tried with a for loop, but no luck.
Thanks!
You can use gson library
You can use Maven or jar file: http://mvnrepository.com/artifact/com.google.code.gson/gson
package com.test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class AppJsonTest {
public static void main(String[] args) {
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(1, "Coca Cola", 0.9, 19));
objList.add(new DataObject(2, "Coca Cola Zero", 0.6, 19));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>() {
}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i = 0; i < inpList.size(); i++) {
DataObject x = inpList.get(i);
System.out.println(x.toString());
}
}
}
class DataObject {
int idProducto;
String Nombre;
Double Precio;
int Cantidad;
public DataObject(int idProducto, String nombre, Double precio, int cantidad) {
this.idProducto = idProducto;
Nombre = nombre;
Precio = precio;
Cantidad = cantidad;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public Double getPrecio() {
return Precio;
}
public void setPrecio(Double precio) {
Precio = precio;
}
public int getCantidad() {
return Cantidad;
}
public void setCantidad(int cantidad) {
Cantidad = cantidad;
}
#Override
public String toString() {
return "DataObject [idProducto=" + idProducto + ", Nombre=" + Nombre + ", Precio=" + Precio + ", Cantidad=" + Cantidad + "]";
}
}
Use gson library to read and write json:
try {
JsonReader reader = new JsonReader(new FileReader("json_file_path.json"));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("idProducto")) {
System.out.println(reader.nextInt());
} else if (name.equals("Nombre")) {
System.out.println(reader.nextString());
} else if (name.equals("Precio")) {
System.out.println(reader.nextDouble());
} else if (name.equals("Cantidad")) {
System.out.println(reader.nextInt());
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
download http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip
You are testing whether the iterator has a next element with i.hasNext(). But you don't consume (or retrieve) this next element by i.next() which is typically in the first statement of the looped block. Therefore i.hasNext() will return true forever.
EDIT: You probably want to set object to i.next() because in your code snippet it always remains at the 0's element you assigned before the loop.
There are many open source libraries, present to parse json to object or just to read and write json values. If you want to read and write json then you can use org.json library.
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values :-
String id = jsonObj.getString("pageInfo");
You can see complete example here :-
How to parse Json in java
If you want to parse your json to particular POJO and then use that pojo to get values, then use jackson-databind library, this will parse your json to POJO class :-
ObjectMapper mapper = new ObjectMapper();
book = mapper.readValue(json, Book.class);
You can see complete example here, How to parse json in java
I am trying to write an automated Java test where the code will go to a specified URL, read the JSON data and print it up.
Here is the JSON I am trying to access;
{
"status": "success",
"records": [
{
"timestamp": 1381222871868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222901868,
"deviceId": "288",
"temperature": 17
},
{
"timestamp": 1381222931868,
"deviceId": "288",
"temperature": 17
},
]}
As you can see I only have 3 elements, Timestamp, DeviceId and Temperature.
What I am ultimately aiming for it to be able to get 2 Timestamp values and take one value away from the other, if that is possible.
Anyway I have been trying to do this all day and am having no luck whatsoever. I was recommended to use Gson and I have included the jar files into my classpath.
If anyone knows anything or can help me in any way it would be much appreciated as I have exhausted Google and myself trying to work this out.
Here is the code I have to display the full list, but I do not fully understand it and so far can't manipulate it to my advantage;
public static void main(String[] args) throws Exception
{
String jsonString = callURL("http://localhost:8000/eem/api/v1/metrics/temperature/288");
System.out.println("\n\njsonString: " + jsonString);
// Replace this try catch block for all below subsequent examples
/*try
{
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e)
{
e.printStackTrace();
}*/
try
{
JSONArray jsonArray = new JSONArray(jsonString);
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++)
{ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject # i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public static String callURL(String myURL)
{
//System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try
{
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
{
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null)
{
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null)
{
int cp;
while ((cp = bufferedReader.read()) != -1)
{
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
}
catch (Exception e)
{
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
Cheers
I had read the values from file but you can read from URL, the extracting process code is present inside extractJson() method.
public static void main(String [] args)
{
try
{
FileInputStream fis=new FileInputStream("testjson.json");
int b=0;
String val="";
while((b=fis.read())!=-1)
{
val=val+(char)b;
}
extractJson(val);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void extractJson(String json)
{
try
{
JSONObject jobject=new JSONObject(json);
System.out.println("Json object Length: "+jobject.length());
System.out.println("Status: "+jobject.getString("status"));
JSONArray jarray=new JSONArray(jobject.getString("records"));
System.out.println("Json array Length: "+jarray.length());
for(int j=0;j<jarray.length();j++)
{
JSONObject tempObject=jarray.getJSONObject(j);
System.out.println("Timestamp: "+tempObject.getString("timestamp"));
System.out.println("Device Id: "+tempObject.getString("deviceId"));
System.out.println("Temperature: "+tempObject.getString("temperature"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
You could use ArrayList to store the values which will be available inside for loop. From your question you need to pass jsonString this variable to the extractJson() method. Use org.json jar file to process json. If you could alter this for gson then it'll be good for your requirement.
here's how to do it via Google-Gson
class MyRecord
{
private long timestamp;
private String deviceId;
private Integer temperature;
//Getters & setters
}
public static void main(String... args){
String myJsonString=callUrl("http://mydomain.com/x.json");
JsonParser jp = new JsonParser();
JsonElement ele = jp.parse(myJsonString);
Gson gg = new Gson();
Type type = new TypeToken<List<MyRecord>>() {
}.getType();
List<MyRecord> lst= gg.fromJson(ele.getAsJsonObject().get("records"), type);
//Now the json is parsed in a List of MyRecord, do whatever you want to with it
}
An "high-level" Gson parsing answer:
package stackoverflow.questions.q19252374;
import java.util.List;
import com.google.gson.Gson;
public class Q19252374 {
class Record {
Long timestamp;
String deviceId;
Long temperature;
}
class Container {
List<Record> records;
}
public static void main(String[] args) {
String json = "{ \"status\": \"success\", \"records\": [{\"timestamp\": 1381222871868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222901868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222931868,\"deviceId\": \"288\",\"temperature\": 17 } ]} ";
Gson g = new Gson();
Container c = g.fromJson(json, Container.class);
for (Record r : c.records)
System.out.println(r.timestamp);
}
}
Of course this is the result:
1381222871868
1381222901868
1381222931868
This is the program i wrote:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
/**
*
* #author 311001
*/
public class NewClass {
public static void main(String args[]) {
JSONObject parentData = new JSONObject();
JSONObject childData = new JSONObject();
try {
parentData.put("command", "login");
parentData.put("uid", "123123123");
childData.put("uid", "007");
childData.put("username", "sup");
childData.put("password", "bros");
parentData.put("params", childData);
System.out.println(parentData);
Map<String, String> map = new HashMap<>();
Iterator<?> iter = parentData.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
String value = parentData.getString(key);
map.put(key, value);
}
for (Entry<String, String> entry : map.entrySet()) {
System.out.println("key > " + entry.getKey() + " : value = " + entry.getValue());
}
String testData = map.get("params.uid");
System.out.println(testData);
System.out.println("Tokenizing json");
String resultStr = parentData.toString();
System.out.println("String tokens ");
StringTokenizer st = new StringTokenizer(resultStr);
System.out.println(st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
String testDat="abc :: result";
StringTokenizer simpleString = new StringTokenizer(testDat);
System.out.println("Tokenizing simple string");
System.out.println(simpleString.countTokens());
while (simpleString.hasMoreTokens()) {
System.out.println(simpleString.nextToken());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
the output i got:
run:
{"command":"login","uid":"123123123","params":{"uid":"007","username":"sup","password":"bros"}}
key > uid : value = 123123123
key > command : value = login
key > params : value = {"uid":"007","username":"sup","password":"bros"}
null
Tokenizing json
String tokens
1
{"command":"login","uid":"123123123","params":{"uid":"007","username":"sup","password":"bros"}}
Tokenizing simple string
3
abc
::
result
BUILD SUCCESSFUL (total time: 0 seconds)
How can I recieve all the keys in my json object. In case I tokenize why do i get only one string token while for a simple string am getting the correct output 3 tokens.
You can recursively traverse your JsonObject to get all keys.
heres the pseudocode
findKeys(JsonObject obj,List keys){
List<String>keysFromObj=obj.keys();
keys.addAll(keysFromObj);
for(String key:keysFromObj){
if(obj.get(key).getClass()==JSONObject.class){
findKeys(obj.get(key),keys);
}
}
}
So suppose if your object is {"a":1,"b":{"c":"hello","d":4.0}}
the above function should give you ["a","b","c","d"]
But if you want only ["a","c","d"] as your output,you can write-
findKeys(JsonObject obj,List keys){
List<String>keysFromObj=obj.keys();
for(String key:keysFromObj){
if(obj.get(key).getClass()==JSONObject.class){
findKeys(obj.get(key),keys);
}else{
keys.add(key);
}
}
}
I am late to the party, but I am adding here my solution:
Input:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
Retrieve all unique keys:
public static void findAllKeys(Object object, Set<String> finalKeys) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
jsonObject.keySet().forEach(childKey -> {
finalKeys.add(childKey);
findAllKeys(jsonObject.get(childKey), finalKeys);
});
} else if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
IntStream.range(0, jsonArray.length())
.mapToObj(jsonArray::get)
.forEach(o -> findAllKeys(o, finalKeys));
}
}
Usage:
Set<String> finalKeys = new HashSet<>();
findAllKeys(new JSONObject(str), finalKeys);
System.out.println(finalKeys);
Output:
[
GlossEntry,
GlossSee,
SortAs,
GlossList,
title,
GlossDiv,
glossary,
GlossTerm,
GlossDef,
para,
GlossSeeAlso,
ID,
Acronym,
Abbrev
]
Retrieve all unique "full path" keys:
public void findAllKeys(Object object, String key, Set<String> finalKeys) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
jsonObject.keySet().forEach(childKey -> {
findAllKeys(jsonObject.get(childKey), key != null ? key + "." + childKey : childKey, finalKeys);
});
} else if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
finalKeys.add(key);
IntStream.range(0, jsonArray.length())
.mapToObj(jsonArray::get)
.forEach(jsonObject -> findAllKeys(jsonObject, key, finalKeys));
}
else{
finalKeys.add(key);
}
}
Usage:
Set<String> finalKeys = new HashSet<>();
findAllKeys(new JSONObject(jsonStr), null, finalKeys);
System.out.println(finalKeys);
Output:
[
glossary.GlossDiv.GlossList.GlossEntry.ID,
glossary.title,
glossary.GlossDiv.GlossList.GlossEntry.GlossSee,
glossary.GlossDiv.GlossList.GlossEntry.GlossTerm,
glossary.GlossDiv.GlossList.GlossEntry.Acronym,
glossary.GlossDiv.GlossList.GlossEntry.Abbrev,
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para,
glossary.GlossDiv.GlossList.GlossEntry.SortAs,
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso,
glossary.GlossDiv.title
]
Here is one implementation using org.json not org.json.simple
It finds all unique values of a json with the Key:value combination using java.
Input json:
{
d: {
results: [{
__metadata: {
uri:https://google.com,
type: User
},
userId: jmarthens1,
businessPhone: null,
salaryProrating: null,
empId: 2023,
lastModifiedDateTime: Date(1458308558000 + 0000),
finalJobRole: null,
username: jmarthens,
married: false,
futureLeader: null,
salary: 79000.0,
jobRole: Program Manager,
Professional Services,
nickname: null,
salaryLocal: null
}]
}
}
Result:
empId-2023
lastModifiedDateTime-Date(1458308558000+0000)
salary-79000.0
userId-jmarthens1
jobRole-Program Manager, Professional Services
type-User
uri-https://google.com
username-jmarthens
Code:
package test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestClass {
private static StringBuilder strOut = new StringBuilder();
public static void main(String[] args) {
try {
String json = "{\"d\" : {\"results\" : [{\"__metadata\" : {\"uri\" : \"https://apisalesdemo8.successfactors.com:443/odata/v2/User('jmarthens1')\","
+ " \"type\" : \"SFOData.User\"}, \"userId\" : \"jmarthens1\", \"businessPhone\" : null, \"salaryProrating\" : null, \"empId\" : \"2023\", "
+ "\"lastModifiedDateTime\" : \"Date(1458308558000+0000)\", \"finalJobRole\" : null, \"username\" : \"jmarthens\", \"married\" : false, "
+ "\"futureLeader\" : null, \"salary\" : \"79000.0\", \"jobRole\" : \"Program Manager, Professional Services\", \"nickname\" : null, \"salaryLocal\" : null}]}}";
JSONObject inputJson = new JSONObject(json);
List<String> lst = new ArrayList<String>();
lst = findKeysOfJsonObject(inputJson, lst);
try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\temp\\temp.txt"))) {
writer.write(strOut.toString());
}
} catch (JSONException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List<String> findKeysOfJsonArray(JSONArray jsonIn, List<String> keys) {
List<String> keysFromArr = new ArrayList<>();
if (jsonIn != null && jsonIn.length() != 0) {
for (int i = 0; i < jsonIn.length(); i++) {
JSONObject jsonObjIn = jsonIn.getJSONObject(i);
keysFromArr = findKeysOfJsonObject(jsonObjIn, keys);
}
}
return keysFromArr;
}
private static List<String> findKeysOfJsonObject(JSONObject jsonIn, List<String> keys) {
Iterator<String> itr = jsonIn.keys();
List<String> keysFromObj = makeList(itr);
keys.addAll(keysFromObj);
itr = jsonIn.keys();
while (itr.hasNext()) {
String itrStr = itr.next();
// System.out.println("out " + itrStr);
JSONObject jsout = null;
JSONArray jsArr = null;
if (jsonIn.get(itrStr).getClass() == JSONObject.class) {
jsout = jsonIn.getJSONObject(itrStr);
findKeysOfJsonObject(jsout, keys);
} else if (jsonIn.get(itrStr).getClass() == JSONArray.class) {
jsArr = jsonIn.getJSONArray(itrStr);
keys.addAll(findKeysOfJsonArray(jsArr, keys));
} else if (jsonIn.get(itrStr).getClass() == String.class) {
System.out.println(itrStr + "-" + jsonIn.get(itrStr));
strOut.append(itrStr + "," + jsonIn.get(itrStr));
strOut.append(System.lineSeparator());
}
}
return keys;
}
public static List<String> makeList(Iterator<String> iter) {
List<String> list = new ArrayList<String>();
while (iter.hasNext()) {
list.add(iter.next());
}
return list;
}
}
static Set<String> finalListOfKeys = new LinkedHashSet<String>();
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("Absolute path of json file"));
JSONObject jsonObject = (JSONObject) obj;
Set<String> jsonKeys = jsonObject.keySet();
for (String key : jsonKeys) {
Object val = jsonObject.get(key);
if (val instanceof JSONArray) {
JSONArray array = (JSONArray) val;
jsonArray(array, key);
} else if (val instanceof JSONObject) {
JSONObject jsonOb = (JSONObject) val;
jsonObj(jsonOb, key);
} else {
finalListOfKeys.add(key);
System.out.println("Key is : " + key);
}
}
System.out.println("Final List : " + finalListOfKeys);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void jsonObj(JSONObject object, String key2) {
Set<String> innerKeys = object.keySet();
System.out.println("Inner Keys : " + innerKeys);
for (String key : innerKeys) {
System.out.println("Key : " + key);
Object val = object.get(key);
if (val instanceof JSONArray) {
JSONArray array = (JSONArray) val;
jsonArray(array, key2 + "->" + key);
} else if (val instanceof JSONObject) {
JSONObject jsonOb = (JSONObject) val;
jsonObj(jsonOb, key2 + "->" + key);
} else {
finalListOfKeys.add(key2 + "->" + key);
System.out.println("Key is : " + key2 + "->" + key);
}
}
}
public static void jsonArray(JSONArray array, String key) {
if (array.size() == 0) {
finalListOfKeys.add(key);
} else {
for (int i = 0; i < array.size(); i++) {
Object jObject = array.get(i);
if (jObject instanceof JSONObject) {
JSONObject job = (JSONObject) jObject;
System.out.println(job);
jsonObj(job, key);
}
}
}
}