JSON parsing using JSON-Simple not working - java

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

Related

Parsing JSON using Java JSONParser

I'm trying to parse a JSON File. I wrote the code below to parse using Java JSONParser:
public static void parseJSONResponse(JSONObject jsonObj) {
for (Object keyObj : jsonObj.keySet()) {
String key = (String) keyObj;
Object valObj = jsonObj.get(key);
if (valObj instanceof JSONObject) {
parseJSONResponse((JSONObject) valObj);
} else if (valObj instanceof JSONArray) {
System.err.println("ARRAY");
} else {
System.out.println(key + " -> " + valObj.toString());
}
}
}
public static void main(String[] args) {
try {
FileReader reader = new FileReader("C:\\Users\\extract.json");
JSONParser parser = new JSONParser();
Object obj = (JSONObject) parser.parse(reader);
JSONObject object = (JSONObject) (obj);
parseJSONResponse(object);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
It returns me a response like this:
description -> For testing purposes only
indexUpdatedAt -> 1420751985
flags -> ["default","restorable","restorePossibleForType"]
data -> [["row-mfpy.gr8q.cpii","00000000-0000"],["00009","9BCA"]]
columns -> [{"renderTypeName":"meta_data","fieldName":":sid"},{"renderTypeName":"meta_data"}]
I need to further parse "flags", "data" & "columns" to retrieve the values individually. How can i modify my "parseJSONResponse" method to achieve this?

Json Field is String or Object [duplicate]

I have the following json
"notes": {"note": [
{
"content": "Having wisdom teeth removed.",
"from": "employee"
},
{
"content": "Get well soon",
"from": "manager"
}
]},
the issue is that the value coud also be
"notes": "",
or
"notes": {"note": {
"content": "This is a test note.",
"from": "employee"
}},
and storing it in these
public class Notes
{
#SerializedName ("note")
public List<Note> note;
}
public class Note
{
#SerializedName ("content")
public String content;
#SerializedName ("from")
public String from;
}
I believe I solved the issue of not being an array but being an single object by doing this
public class Json {
private static Gson gson;
private static class MyNoteClassTypeAdapter implements JsonDeserializer<List<RequestsDTO.Note>> {
public List<RequestsDTO.Note> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<RequestsDTO.Note> vals = new ArrayList<RequestsDTO.Note>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
vals.add((RequestsDTO.Note) ctx.deserialize(e, RequestsDTO.Note.class));
}
} else if (json.isJsonObject()) {
vals.add((RequestsDTO.Note) ctx.deserialize(json,RequestsDTO.Note.class));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return vals;
}
}
public static Gson getGson()
{
if (gson == null)
{
Type ListType = new TypeToken<List<RequestsDTO.Note>>() {}.getType();
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(DateTime.class, new DateTimeSerializer());
builder.registerTypeAdapter(ListType, new MyNoteClassTypeAdapter());
gson = builder.create();
}
return gson;
}
}
And now I am stuck on when the whole thing just comes back as a string....
Refer the code snippet below to deserialize your json using Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("note");
if(elem.isJsonArray()) { //**Array**
List<Note> notelist = gson.fromJson(elem.toString(), new TypeToken<List<Note>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), Note.class);
} else { //**String**
String note = elem.toString();
}
The idea is try to get "note" field (from "notes" JSONObject) as JSONArray first and if it throws exception that will mean that there is no "note" JSONArray into "notes" JSONObject and that will mean that "note" is JSONObject. The same way we can figure out situation when note field is String.
try {
//String jsonString="{\"notes\": {\"note\": [{\"content\": \"Having wisdom teeth removed.\",\"from\": \"employee\" }, {\"content\": \"Get well soon\", \"from\": \"manager\"} ] }}";
//String jsonString="{\"notes\": { \"note\": {\"content\": \"This is a test note.\",\"from\": \"employee\"}}}";
String jsonString="{\"notes\": { \"note\": \"\"}}";
JSONObject jsonObject=new JSONObject(jsonString);
JSONObject jsonObjectNotes=jsonObject.getJSONObject("notes");
try{
JSONArray jsonArrayNote=jsonObjectNotes.getJSONArray("note");
for (int i = 0; i < jsonArrayNote.length(); i++) {
JSONObject jsonObject2= jsonArrayNote.getJSONObject(i);
String stringContent=jsonObject2.getString( "content");
String stringFrom= jsonObject2.getString( "from");
Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
}
}
catch(JSONException e){
//that means that jsonObjectNotes has no jsonArray with name "notes" and "notes" is jsonObject
try{
JSONObject jsonObject3=jsonObjectNotes.getJSONObject("note");
String stringContent=(String) jsonObject3.get( "content");
String stringFrom=(String) jsonObject3.get( "from");
Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
}
catch(JSONException ex){
//that means that jsonObjectNotes has no jsonObject with name "notes" and "notes" is empty String
String stringNote=jsonObjectNotes.getString("note") ;
Log.e(getClass().getName(), "note is string ="+ stringNote);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
In my example code another get operations can also throw jsonExceptions but I think you get the idea.
Have a look at Genson library http://code.google.com/p/genson/.
If your classes are inner classes make them static.
The following code should solve your problem.
Genson genson = new Genson.Builder().withDeserializerFactory(new NotesDeserializerFactory()).create();
Notes notes = genson.deserialize(in, Notes.class);
// Define a factory so you can delegate the deserialization to existing mechanisms for lists and beans
class NotesDeserializerFactory implements Factory<Deserializer<Notes>> {
#Override
public Deserializer<Notes> create(Type type, Genson genson) {
Converter<List<Note>> noteListConverter = genson.provideConverter(new GenericType<List<Note>>() {}.getType());
Converter<Note> noteConverter = genson.provideConverter(Note.class);
return new NotesDeserializer(noteListConverter, noteConverter);
}
}
// define an implementation for you Notes class so you can handle the different cases
class NotesDeserializer implements Deserializer<Notes> {
private final Converter<List<Note>> noteListConverter;
private final Converter<Note> noteConverter;
public NotesDeserializer(Converter<List<Note>> noteListConverter,
Converter<Note> noteConverter) {
this.noteListConverter = noteListConverter;
this.noteConverter = noteConverter;
}
#Override
public Notes deserialize(ObjectReader reader, Context ctx) throws TransformationException,
IOException {
Notes notes = new Notes();
if (reader.getValueType() == ValueType.ARRAY) notes.note = noteListConverter.deserialize(reader, ctx);
else if (reader.getValueType() == ValueType.OBJECT) notes.note = Arrays.asList(noteConverter.deserialize(reader, ctx));
else { // it is a litteral (string, numeric, boolean, null)
notes.note = new ArrayList<Note>();
}
return notes;
}
}

Parsing data from JSON

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

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

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