how to extract a multiple json objects within objects - java

I'm trying to read a list of episodes (http://epguides.frecar.no/show/bigbangtheory/) from a json file, count the episode titles and print them in the console. However since I'm new to working with json I can't even manage to reach the first title, always returning null. A little help or a small hint towards the right direction would be greatly appreciated.
JSONParser parser = new JSONParser();
try {
File tmpDir = new File("src/bigbangtheory.json");
boolean exists = tmpDir.exists();
if (exists==true) System.out.println("file exists");
else System.out.println("file doesn't exist");
Object obj = parser.parse(new FileReader("src/bigbangtheory.json"));
JSONObject season = (JSONObject) obj;
System.out.println(obj);
Object title = (Object) season.get("title");
System.out.println(title);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

The JSON file contains an object holding all seasons.
From that object you need to extract a specific season and episode before you're able to read a title.
Object obj = parser.parse(new FileReader("src/bigbangtheory.json"));
JSONObject seasons = (JSONObject) obj;
System.out.println(seasons);
JSONArray seasonTwo = (JSONArray) seasons.get("2");
System.out.println(seasonTwo);
for (Object o : seasonTwo) {
JSONObject episode = (JSONObject) o;
Object title = episode.get("title");
System.out.println(title);
}

Related

Why does the following string show a JSONException?

The following code generates a org.json.JSONException: No value for eqlocation.
https://jsonformatter.curiousconcept.com/ doesn't show any error for the string.
String message="{"eqlocation": [{"lat": 38.3904, "lon": 73.8278}, {"lat": 19.0119, "lon": 95.5838}, {"lat": 12.9046, "lon": 92.2347}, {"lat": 34.1968, "lon": 80.7091}], "cydata": []}";
try {
JSONObject jsonObj = new JSONObject(message);
Log.v("fromjson",jsonObj.get("eqlocation").toString());
}
catch (JSONException e){
e.printStackTrace();
Toast.makeText(getContext(),"No JSON received",Toast.LENGTH_SHORT).show();
}
You need to escape the quotes inside the string and you can use a parser to simplify the proccess.
JSONParser parser = new JSONParser();
String message = "{\"eqlocation\":[{\"lat\":38.3904,\"lon\":73.8278},{\"lat\":19.0119,\"lon\":95.5838},{\"lat\":12.9046,\"lon\":92.2347},{\"lat\":34.1968,\"lon\":80.7091}],\"cydata\":[]}";
try {
Object obj = parser.parse(message);
JSONObject obj2 = (JSONObject) obj;
Log.v("fromjson",obj2.get("eqlocation").toString());
}
catch (ParseException pe){
pe.printStackTrace();
}
}
You can see it working in plain java here: https://repl.it/repls/InvolvedSuperbSupport
The json looks fine but you're trying to parse an Array data.
Instead, you can try this:
try {
JSONObject jsonObj = new JSONObject(message);
JSONArray jArray = jsonObj.getJSONArray("eqlocation"); // get the array
for(int i=0; i < jArray.length(); i++) { // loop through the items
JSONObject json_data = jArray.getJSONObject(i);
Log.v("fromjson", json_data.getString("lat")); // get latitute here
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(),"No JSON received",Toast.LENGTH_SHORT).show();
}
Note: However, the way you initialized the String is not correct. You'll need to escape the quotes.

parse a json file lost structure of data - JAVA

i have to create a json file that contain some object (a name, a string list and a date list). the problem is when i have to write and read date in LocalDate format.
if i write and then i print the jsonObject, the format of the date is ok. but when i do the parse and suddedly i print the object, the format of the date is wrong.
this is the code for write in the file:
public void aggiungi(){
JSONObject obj = new JSONObject();
obj.put("name", this.name);
JSONArray listMov = new JSONArray();
JSONArray listData = new JSONArray();
for(int i =0; i<this.movimenti.size(); i++){
listMov.add(movimenti.get(i));
listData.add(data.get(i));
}
obj.put("data", listData);
obj.put("mov", listMov);
File file=new File("file.json");
try {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(obj.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(obj);
}
and the final println print:
{"data":[2015-03-02,2015-04-05,2015-06-10],"mov":
["F24","PagoBancomat","Bollettino"],"name":"Stefano"}
and this is the code for read:
JSONParser parser = new JSONParser();//per decodifica
Object obj;
try {
obj = parser.parse(new FileReader("file.json"));
JSONObject jsonObj = (JSONObject) obj;
String name= (String) jsonObj.get("name");
JSONArray list = (JSONArray) jsonObj.get("mov");
JSONArray listData = (JSONArray) jsonObj.get("data");
System.out.println(jsonObj);
Iterator<String> iteratorM = list.iterator();
Iterator<LocalDate> iteratorD = listData.iterator();
ArrayList<String> mov =new ArrayList<String>(list.size());
ArrayList<LocalDate> data =new ArrayList<LocalDate>(list.size());
while(iteratorM.hasNext()){
mov.add(iteratorM.next());
}
while(iteratorD.hasNext()){
data.add(iteratorD.next());
}
ContoCorrente cc = new ContoCorrente(data, mov, name);
Contatore task = new Contatore(cc);
this.executeTask(task);
} 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();
}
and print
{"data":[2015,-3,-2,2015,-4,-5,2015,-6,-10],"mov":
["F24","PagoBancomat","Bollettino"],"name":"Stefano"}
the last print separes the structure of a date, separing day, month and year.
what i do wrong in the code?
thanks you and sorry for my bad english
Instead of setting as a data object in JSON,first parse it to String using dateformatters then set it in JSON object as string.
Use DateTimeFormatter for converting LocalDate into String value, assuming data as object of ArrayList<LocalDate> ;
JSONArray listMov = new JSONArray();
JSONArray listData = new JSONArray();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for(int i =0; i<this.movimenti.size(); i++){
listMov.add(movimenti.get(i));
listData.add(data.get(i).format(formatter));
}

getJSONObject not working in Java

I'm trying to parse json file in my java project using this below code,
JSONParser parser = new JSONParser();
try {
Object obj = null;
try {
obj = parser.parse(new FileReader(new File("json/branch_list.json")));
} catch (org.json.simple.parser.ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
System.out.println("Branches are :");
JSONArray listOfBranches = (JSONArray) jsonObject.get("branch_list");
Iterator iterator = listOfBranches.iterator();
for (int i = 0; i < listOfBranches.size(); i++) {
JSONObject c = listOfBranches.getJSONObject(i);
System.out.println("Branch are :" + listOfBranches.get(i));
}
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
From above code when i'm using this two below lines
JSONObject c = listOfBranches.getJSONObject(i);
String branchName = c.getString("branch_name");
Its shows the method getJSONObject(int) is undefined for the type JSONArray
And I'm getting the whole object when using this below code,
System.out.println("Branch are :"+listOfBranches.get(i));
It prints like this,
{"branch_name":"AMM"}
from this I want to get branch name using the key "branch_name". But I could not able to do this because of "the method getJSONObject(int) is undefined for the type JSONArray" exception
And I have added json-simple jar in my project. Could you please suggest me any idea to do this? Thanks in advance.
If i undestood you right then:
JSONObject item = (JSONObject)listOfBranches.get(0);
String branchName = (String)item.get("branch_name");
i think you should use org.json instead of simple-json. The method getJSONObject(i) is available in org.json. Refer to the below url for more detail.
https://stackoverflow.com/questions/2591098/how-to-parse-json

Reading the first record from array of Json records in a json file in JAVA

How to get the first record from a JSON File that contains array of JSON Records
Sample File:
[
{"l7ProtocolID":"dhcp","packets_out":1,"bytes_out":400,"start_time":1454281199898,"flow_sample":0,"duration":102,"path":["base","ip","udp","dhcp"],"bytes_in":1200,"l4":[{"client":"68","server":"67","level":0}],"l2":[{"client":"52:54:00:50:04:B2","server":"FF:FF:FF:FF:FF:FF","level":0}],"l3":[{"client":"::ffff:0.0.0.0","server":"::ffff:255.255.255.255","level":0}],"flow_id":"81454281200000731489","applicationID":"dhcp","packets_in":1}
{"l7ProtocolID":"dhcp","packets_out":1,"bytes_out":400,"start_time":1454281199898,"flow_sample":0,"duration":102,"path":["base","ip","udp","dhcp"],"bytes_in":1200,"l4":[{"client":"68","server":"67","level":0}],"l2":[{"client":"52:54:00:50:04:B2","server":"FF:FF:FF:FF:FF:FF","level":0}],"l3":[{"client":"::ffff:0.0.0.0","server":"::ffff:255.255.255.255","level":0}],"flow_id":"81454281200000731489","applicationID":"dhcp","packets_in":1}
Record n.....
]
And simillarly there might be 1000+ records in the file.
I want to fetch the first record out of this file.
The below code doesn't load the whole file as a String in memory. Although, the whole array would be in memory. For example, Gson would load about 10KB of file bytes into buffer at a time, and parse each row and add to the array. But, all 1000 objects will be on the heap in the array.
Partial Streaming suitable for most cases
public static void readDom() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
Gson gson = new GsonBuilder().create();
Person[] people = gson.fromJson(reader, Person[].class);
System.out.println("Object mode: " + people[0]);
} catch (FileNotFoundException ex) {
...
} finally {
...
}
}
Above code is more efficient than below:
One shot read (Only for small files)
String fileContents = FileUtils.readAsString(file);
Person[] persons = gson.fromJson(fileContents, Person[].class);
First approach could be okay for upto 5k-10k rows at a time. But, beyond 10k, even first approach may not be great.
This third option is the best for large data. Iterate and read one row at a time and stop whenever you want.
True Streaming
public static void readStream() {
try {
JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
Gson gson = new GsonBuilder().create();
// Read file in stream mode
reader.beginArray();
while (reader.hasNext()) {
// Read data into object model
Person person = gson.fromJson(reader, Person.class);
if (person.getId() == 0 ) {
System.out.println("Stream mode: " + person);
}
break;
}
reader.close();
} catch (UnsupportedEncodingException ex) {
...
} catch (IOException ex) {
...
}
}
Source: Reading JSON as Stream using GSON
Dealing with JSON parsing without matching POJO structures
If you don't want to take the trouble of creating a matching POJO object graph structure, you could just instruct GSON to treat each row as a HashMap.
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> thisRow = gson.fromJson(reader, type);
Got the solution using org.JSON.simple library
public String ReadJsonFromFile(String fileName){
JSONParser parser = new JSONParser();
String firstRecord = null;
try {
JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(fileName));
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
firstRecord = jsonObject.toString();
} catch (FileNotFoundException e) {
LOG.info("JSON -> Can't read from file: File Not Found");
e.printStackTrace();
} catch (IOException e) {
LOG.info("JSON -> Can't read File : IO Exception");
e.printStackTrace();
} catch (ParseException e) {
LOG.info("JSON -> Can't Parse JSON in File");
e.printStackTrace();
}
return firstRecord;
}

how to avoid a Json array when i'm fetching data

i'm fetching Json data in java, and my Json have different structure and not always the same. Example :
{"0":{"id"="255",name="example"},"1":{"news_id":"47221","news_infos":{"title":"test","date":"2014-05-14 17:44:02","shared":"47"},"website":"test.it"},"3":{"id"="55885",name="foo"}}
This is just an example. What i want to know is how i can skip the second one, we suppose the second one is a JsonArray.
This is an example of what I'm doing in java ;
for (int i = 0; i < jObj.length() ; i++) {
try {
JSONObject obj = jObj.getJSONObject(i); //Suppose that every entry in the Json is an object and not a JsonArray.
if (!obj.isNull("titrenews")) {
Home home = new Home();
Log.i("Infos","Yes");
home.setNomC(obj.getString("titrenews"));
home.setPhotoAr(photoNews);
home.setText(obj.getString("textnews"));
home.setNbrSick(obj.getString("sicks"));
homeList.add(home);
}
}catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
To sum up the problem i have a json data. composed of JsonObject and JsonArray, and what i want is to skip the jsonArray entry and avoid it
so any solutions please !
Try this approach:
for (Object obj : jObj) {
if (obj instanceof JSONObject){
//do something
}
else if (obj instanceof JSONArray){
continue;//skip
}
}

Categories