Parsing google json with java - 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

Related

How to parse this json from file

How I can parse this json file using SimpleJson lib, the format is like this:
Thank you
my file looks like this: json file with Array of Json inside;
{"data":[{"host":"hostname1","port":2049,"open":"false", "info":" "},
{"host":"hostname1","port":2049,"open":"false", "info":" "},
{"host":"hostname2","port":2049,"open":"false", "info":" "},
{"host":"hostname3","port":2049,"open":"false", "info":" "},
{"host":"hostname4","port":443,"open":"false", "info":" "},
{"host":"hostname5","port":443,"open":"false","info":" "},
{"host":"hostname6","port":61208,"open":"false","info":" "},
{"host":"hostname7","port":139,"open":"false","info":" "}]}
my code at this moment:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("D:/file.json"));
JSONArray jsonObject = (JSONArray) obj;
JSONObject arr = (JSONObject) jsonObject.get(0);
JSONArray arguments = (JSONArray) arr.get("arguments");
System.out.println("arguments>>>>>>>>> "+arguments);
for(int i = 0 ; i< arguments.size() ;i++){
JSONObject object = (JSONObject) arguments.get(i);
System.out.println(object);
return object;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
I did manually like this:
//data
JSONObject obj1 = new JSONObject();
obj1.put("host", "mkyong.com");
obj1.put("port", "555");
obj1.put("open", "false");
obj1.put("info", "");
JSONObject obj2 = new JSONObject();
obj2.put("host", "mkyong.com");
obj2.put("port", "555");
obj2.put("open", "false");
obj2.put("info", "");
JSONArray list = new JSONArray();
list.add(obj2);
JSONObject datajson = new JSONObject();
datajson.put("data", list);
It looks like JSON.simple is an old Google library. I think you need to switch to GSON. Here is sample code that demos how to read the given JSON. The Key here is that the original JSON object holds an array of JSON objects as the value of key data.
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
/**
*
* #author blj0011
*/
public class JsonSimpleReaderExample
{
public static void main(String[] args)
{
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("file.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("data");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObjectInJsonArray = (JSONObject) iterator.next();
System.out.println(jsonObjectInJsonArray.get("host"));
}
}
catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
Output:
hostname1
hostname1
hostname2
hostname3
hostname4
hostname5
hostname6
hostname7

Convert JSON string to json objects

I have a json string returning:
[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk#connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]
There are several records here, I can't find a way to convert this json string to individual objects. I'm using the following to read in the data:
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
}
I've tried the simple json libary but the parser mixes up the string, Which is not ideal as I need to output the data to rows object by object to jtables.
Any help would be appreciated.
Solved it with the below with GSON. Many thanks everyone!
JsonElement jelement = new JsonParser().parse(response.toString());
JsonArray jarray = jelement.getAsJsonArray();
JsonObject jobject = jarray.get(0).getAsJsonObject();
System.out.println(jobject.get("FIRST_NAME"));
You can use something like this:
public class ObjectSerializer {
private static ObjectMapper objectMapper;
#Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
ObjectSerializer.objectMapper = objectMapper;
}
public static <T> T getObject(Object obj, Class<T> class1) {
String jsonObj = "";
T userDto = null;
try {
jsonObj = objectMapper.writeValueAsString(obj);
userDto = (T) objectMapper.readValue(jsonObj, class1);
System.out.println(jsonObj);
} catch (JsonProcessingException jpe) {
} catch (IOException e) {
e.printStackTrace();
}
return userDto;
}
Pass your JSON Object to this method alogn with class name and it will set the JSON data to that respective class.
Note:
Class must have the same variables as in the JSON that you want to map with it.
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
see this
You can use Jackson to convert JSON to an object.Include the dependency :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Then make a POJO class to store the JSON .The pojo class should reflect the json string structure and should have appropriate fields to map the values(Here in sample code Staff.class is a pojo class).Then, by using ObjectMapper class you can convert the JSON string to a java object as follows :
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(response.toString(), Staff.class);
Another simple method to read a JSON string and convert it into an object is :
JSON String:
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
public class JSONReadExample
{
public static void main(String[] args) throws Exception
{
// parsing file "JSONExample.json"
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
// getting firstName and lastName
String firstName = (String) jo.get("firstName");
String lastName = (String) jo.get("lastName");
System.out.println(firstName);
System.out.println(lastName);
// getting age
long age = (long) jo.get("age");
System.out.println(age);
// getting address
Map address = ((Map)jo.get("address"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
// getting phoneNumbers
JSONArray ja = (JSONArray) jo.get("phoneNumbers");
// iterating phoneNumbers
Iterator itr2 = ja.iterator();
while (itr2.hasNext())
{
itr1 = ((Map) itr2.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
For reference:
https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
What you have basically is this :
[
{
"TRAIN_JOURNEY_STAFF":[
],
"ID":15,
"EMAIL_ADDRESS":"jk#connectedrail.com",
"PASSWORD":"test",
"FIRST_NAME":"Joe",
"LAST_NAME":"Kevin",
"DATE_OF_BIRTH":"1996-04-20T00:00:00",
"GENDER":"Male",
"STAFF_ROLE":"Conductor",
"PHOTO":null
},
{
}
]
You can use JSON constructor to serialize this array to an Array of JSONObjects.
Try looking for JSONObject and JSONArray classes in Java.
The constructor basically takes the stringified JSON (which you already have).

java : create nested json object from String

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);

Creating a JSON object

I am making a JSON request to server using Java. Here is the following parameters.
{method:'SearchBySearchConfiguration',params:[{{SearchCriteria:'%arriva',
IsAccountSearch:true,IsContactSearch:false,SearchByName:true,SearchByAddress:false
CRMTextValues:[], CRMCurrencyValues:[]}]}
I could do this way.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
How do I add the rest of params, in name-value pair to JSON object?
Thanks in advance!
One way I can think of is using the org.json library. I wrote a sample to build part of your request object:
public static void main(String[] args) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("method", "SearchBySearchConfiguration");
JSONArray jsonArray = new JSONArray();
JSONObject innerRecord = new JSONObject();
innerRecord.put("SearchCriteria", "%arriva");
innerRecord.put("IsAccountSearch", true);
jsonArray.put(innerRecord);
jsonObject.put("params",jsonArray);
System.out.println("jsonObject :"+jsonObject);
}
The output is :
jsonObject :{"method":"SearchBySearchConfiguration","params":[{"IsAccountSearch":true,"SearchCriteria":"%arriva"}]}
Another technique would be to build Java objects that resemble your request structure. You can then convert it into json using Jackson library's ObjectMapper class.
In both cases once you get the json string, you can directly write it into the request body.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
JSONArray paramsArr = new JSONArray();
JSONObject arrobj = new JSONOject();
arrobj.put("SearchCriteria","%arriva");
arrobj.put("IsAccountSearch","true");
arrobj.put("IsContactSearch","false");
arrobj.put("SearchByName","true");
arrobj.put("SearchByAddress","false");
arrobj.put("CRMTextValues",new JSONArray());
arrobj.put("CRMCurrencyValues",new JSONArray());
paramsArr.put(arrobj);
json.put("params",paramsArr);
The you can create JSONArray and put that array in JSONObject
Its Better to use gson for this.
First you need to create classs with following members :
public class TestClass{
private String method;
private ParamClass params;
}
public class ParamClass{
private String SearchCriteria;
private boolean IsAccountSearch;
private boolean IsContactSearch;
private boolean SearchByName;
private boolean SearchByAddress;
private String[] CRMTextValues;
private String[] CRMCurrencyValues;
}
Usage :
Serializing :
Gson gson = new Gson();
String jsonString = gson.toJson(testClassObject);
Deserializing :
Gson gson = new Gson();
TestClass testClassObject = gson.fromJson(jsonString , TestClass.class);
See this below example, where a JSONArray is returned and then how i am converting it in JSONObject form...
public JSONArray go() throws IOException, JSONException {
JSONArray json = readJsonFromUrl("http://www.xxxxxxxx.com/AppData.aspx");
return json;
}
JSONArray jarr;
for(int i=0 ; i<jarr.length() ; i++){
JSONObject jobj = jarr.getJSONObject(i);
String mainText = new String();
String provText = new String();
String couText = new String();
try{
mainText = jobj.getString("Overview");
System.out.println(mainText);
}catch(Exception ex){}
try{
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
}catch(Exception ex){}
try{
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
}catch(Exception ex){}
Jackson is a very efficient to do JSON Parsing
See this link:
http://jackson.codehaus.org/
Gson is provided by google which is also a good way to handle JSON.
To add params, JSONArray is used.
Inside params, we use JSONObject to add data such as SearchByAddress, IsAccountSearch ..etc.
Reference http://www.mkyong.com/java/json-simple-example-read-and-write-json/
package com.test.json;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("method", "SearchBySearchConfiguration");
JSONArray list = new JSONArray();
JSONObject innerObj = new JSONObject();
innerObj.put("SearchCriteria","%arriva" );
innerObj.put("IsAccountSearch",true);
innerObj.put("IsContactSearch",false);
innerObj.put("SearchByName",true);
innerObj.put("SearchByAddress",false);
innerObj.put("CRMTextValues",new JSONArray());
innerObj.put("CRMCurrencyValues",new JSONArray());
list.add(innerObj);
obj.put("params", list);
System.out.print(obj);
}
}

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