Parsing data from JSON - java

Ok so I got here is my sample JSON:
{
"messages":[
{
"receiver":"60:51:2c:93:6e:02",
"sender":"60:51:2c:93:6e:01",
"location":[
{
"longitude":"26.89478",
"latitude":"122.779953"
}
]
}
]
,"isSuccess":"true"
}
How can I retrieve every data inside it?
This is only what I got:
JSONObject jsonObject = parser.makeHttpRequest(someurl);
JSONArray messages = jsonObject.getJSONArray("messages");

If you are using the org.json lib
String json = "{\"messages\":[{\"receiver\":\"60:51:2c:93:6e:02\",\"sender\":\"60:51:2c:93:6e:01\",\"location\":[{\"longitude\":\"26.89478\",\"latitude\":\"122.779953\"}]}],\"isSuccess\":\"true\"}";
try {
JSONObject jsonObject = new JSONObject(json);
Boolean isSuccess = jsonObject.getBoolean("isSuccess");
JSONArray messages = jsonObject.getJSONArray("messages");
JSONObject firstElement = messages.getJSONObject(0);
String sender = firstElement.getString("sender");
JSONArray locationArray = firstElement.getJSONArray("location");
JSONObject firstLocation = locationArray.getJSONObject(0);
Double lng = firstLocation.getDouble("longitude");
Double lat = firstLocation.getDouble("latitude");
Log.d("Result", "isSuccess: " + String.valueOf(isSuccess)
+"\n Sender: " + String.valueOf(sender)
+"\n Latitude: " + String.valueOf(lat)
+"\n Longitude: " + String.valueOf(lng));
} catch (JSONException e) {
e.printStackTrace();
}
Or with less lines of code
Boolean isSuccess = jsonObject.getBoolean("isSuccess");
String sender = jsonObject.getJSONArray("messages").getJSONObject(0).getString("sender");
JSONObject firstLocation = jsonObject.getJSONArray("messages").getJSONObject(0).getJSONArray("location").getJSONObject(0);
Double lng = firstLocation.getDouble("longitude");
Double lat = firstLocation.getDouble("latitude");
What I also like with this library are the opt..() methods like optDouble() or optJSONObject() to avoid nested try/catch and define a default value if the key you are looking for doesn't exist.

I would suggest use JSCKSON APIs
refer below code
public static void main(String[] args) {
System.out.println("Hi");
String json = "{\"messages\":[{\"receiver\":\"60:51:2c:93:6e:02\",\"sender\":\"60:51:2c:93:6e:01\",\"location\":[{\"longitude\":\"26.89478\",\"latitude\":\"122.779953\"}]}],\"isSuccess\":\"true\"}";
ObjectMapper om = new ObjectMapper();
try {
JsonNode node = om.readTree(json);
System.out.println(node.get("messages").get(0).get("receiver"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

How to put Json object through loop

I want to loop through the questionnaires by using the for loop to set the value of the EMAIL_TO_CLIENT_IND.
The value inside the "path" is QUESTIONNAIRES/SUB_QUESTION/EMAIL_TO_CLIENT_IND.
The first "if" is if the level path in JSON is just one Ex. "Questionnaires". And the "else" is for the path more than 1 Ex. "Questionnaires/Question".
My current idea is put the jObject.getJSONObject() inside the "else" for loop.
You can use the JSONArray as follows
String json="{\"QUESTIONNAIRES\":[{\n" +
" \"SUB_QUESTION\":[{\n" +
" \"EMAIL_TO_CLIENT_IND\":\"N\"\n" +
" }]\n" +
"}]}";
try {
JSONObject mainObject=new JSONObject(json);
JSONArray questionnairesArray=mainObject.getJSONArray("QUESTIONNAIRES");
for (int i=0;i<questionnairesArray.length();i++){
JSONObject questionnairesObject= (JSONObject) questionnairesArray.get(i);
JSONArray subQuestionArray=questionnairesObject.getJSONArray("SUB_QUESTION");
for (int j=0;j<subQuestionArray.length();j++){
JSONObject subQuestionObject= (JSONObject) subQuestionArray.get(i);
subQuestionObject.put("EMAIL_TO_CLIENT_IND","Y");
}
}
Log.e("Output",mainObject.toString());
} catch (JSONException e) {
Log.e("Exception",e.getMessage());
}
Edited
can be solved using GSON library also
//frame data classes
class Response {
#SerializedName("QUESTIONNAIRES")
private List<Questionaire> questionaireList;
public List<Questionaire> getQuestionaireList() {
return questionaireList;
}
public void setQuestionaireList(List<Questionaire> questionaireList) {
this.questionaireList = questionaireList;
}
}
class Questionaire {
#SerializedName("SUB_QUESTION")
private List<SubQuestion> subQuestionList;
public List<SubQuestion> getSubQuestionList() {
return subQuestionList;
}
public void setSubQuestionList(List<SubQuestion> subQuestionList) {
this.subQuestionList = subQuestionList;
}
}
class SubQuestion {
#SerializedName("EMAIL_TO_CLIENT_IND")
private String emailToClientId;
public String getEmailToClientId() {
return emailToClientId;
}
public void setEmailToClientId(String emailToClientId) {
this.emailToClientId = emailToClientId;
}
}
//loop through data using GSON
Gson gson = new Gson();
String json = "{\"QUESTIONNAIRES\":[{\n" +
" \"SUB_QUESTION\":[{\n" +
" \"EMAIL_TO_CLIENT_IND\":\"N\"\n" +
" }]\n" +
"}]}";
Response response = gson.fromJson(json, Response.class);
for (Questionaire questionnaire : response.getQuestionaireList()) {
for (SubQuestion subQuestion : questionnaire.getSubQuestionList()) {
subQuestion.setEmailToClientId("Y");
}
}
Log.e("Output", gson.toJson(response));

Handle array data from server android

in my application data coming from a server in the form of an array,
i cant handle the data i will share my code please help me.
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
s_key = jsonObject.getString("initKey");
s_iv = jsonObject.getString("initIv");
sec_url = jsonObject.getString("url");
s_init_hash = jsonObject.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
There is no JSONArray
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject .getJSONObject(i);
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
You Response is JSONObject not in JSONArray check it
FYI
{ } brackets means JSONObject
[ ] brackets means JSONArray
Parse your json like this
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
} catch (JSONException e) {
e.printStackTrace();
}
}
data Is not Json Array cause it start with {} it`s Json Object
Json Array start with []
So you need To use
SONObject jsonObjectData = jsonObject .getJSONObject(i);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
response
{
"status": "success",
"data": {
"initKey": "abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
Code
try {
JSONObject outerJsonObject=new JSONObject(response);
String status=outerJsonObject.getString("status");
if(status.equals("success"))
{
JSONObject innerJsonObjectData=outerJsonObject.getJSONObject("data");
String initKey =innerJsonObjectData.getString("initKey");
String initHash =innerJsonObjectData.getString("initHash");
String initIv =innerJsonObjectData.getString("initIv");
String versionNo =innerJsonObjectData.getString("versionNo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Comments
/*
{
//outerJsonObject
"status":"success",
"data": // innerJsonObjectData
{
"initKey":"abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
*/
When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example:
[{"name":"item 1"},{"name": "item2} ]
On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item. For example:
{"name": "item1", "description":"a JSON object"}
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject data = jsonObject. getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}

How to gather data from a JSON URL and display it

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

JSON parsing using JSON-Simple not working

I'm having an issue trying to parse a string using json-simple, this is the sample string:
{
"items": [
{
"id": "uy0nALQEAM4",
"kind": "youtube#video",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/x3SYRGDdvDsN5QOd7AYVzGOJQlM\"",
"status": {
"uploadStatus": "processed",
"privacyStatus": "public",
"license": "youtube",
"embeddable": true,
"publicStatsViewable": true
}
}
]
}
This is my code:
JSONParser parser = new JSONParser();
Object obj = parser.parse(result);
JSONObject jsonObject = (JSONObject) obj;
System.out.println("privacyStatus: "
+ (String) jsonObject.get("items[0].status.privacyStatus")
+ "\nembeddable: "
+ (String) jsonObject.get("items[0].status.embeddable")
+ "\npublicStatsViewable: "
+ (String) jsonObject.get("items[0].status.publicStatsViewable"));
The output is:
privacyStatus: null
embeddable: null
publicStatsViewable: null
What stupid mistake am I making?
I was able to get the privacyStatus this way, however I cant seem to see anything in their documentation where they show any examples of using a chained get statement like the ones you have.
((JSONObject)((JSONObject)((JSONArray) jsonObject.get("items")).get(0)).get("status")).get("privacyStatus")
Edit: I found this little snippet in some android code I have It will work with the http://json.org/java/ library (this is very similar if not the same as the android JSON library)
public static void main(String[] args)
{
// this is the same JSON string in the OP
String jsonString = "{ \"items\": [ { \"id\": \"uy0nALQEAM4\", \"kind\": \"youtube#video\", \"etag\": \"\\\"g-RLCMLrfPIk8n3AxYYPPliWWoo/x3SYRGDdvDsN5QOd7AYVzGOJQlM\\\"\", \"status\": { \"uploadStatus\":\"processed\", \"privacyStatus\": \"public\", \"license\": \"youtube\", \"embeddable\": true, \"publicStatsViewable\": true } } ]}";
JSONObject object = new JSONObject(jsonString);
try {
String myValue = (String)getJSONValue("items[0].status.privacyStatus", object);
System.out.println(myValue);
} catch (JSONException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static Object getJSONValue(String exp, JSONObject obj) throws JSONException {
try {
String [] expressions = exp.split("[\\.|\\[|\\]]");
Object currentObject = obj;
for(int i=0; i < expressions.length; i++) {
if(!expressions[i].trim().equals("")) {
System.out.println(expressions[i] + " " + currentObject);
if(currentObject instanceof JSONObject) {
Method method = currentObject.getClass().getDeclaredMethod("get", String.class);
currentObject = method.invoke(currentObject, expressions[i]);
} else if(currentObject instanceof JSONArray) {
Method method = currentObject.getClass().getDeclaredMethod("get", Integer.TYPE);
currentObject = method.invoke(currentObject, Integer.valueOf(expressions[i]));
} else {
throw new JSONException("Couldnt access property " + expressions[i] + " from " + currentObject.getClass().getName());
}
}
}
return currentObject;
} catch (NoSuchMethodException ex) {
throw new JSONException(ex);
} catch (IllegalAccessException ex) {
throw new JSONException(ex);
} catch (IllegalArgumentException ex) {
throw new JSONException(ex);
} catch (InvocationTargetException ex) {
throw new JSONException(ex);
}
}
I guess it's a library limitation to solve it in a clean way. I found minimal library:
https://github.com/ralfstx/minimal-json
Which is very nice and clean. Then did the following to do what I wanted:
JsonObject jsonObject = JsonObject.readFrom(result.toString())
.get("items").asArray().get(0).asObject().get("status").asObject();
Then I can do:
boolean isPublic = jsonObject.get("privacyStatus").asString().equals("public");
boolean isEmbbedable = jsonObject.get("embeddable").asBoolean();

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