getJSONObject not working in Java - 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

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

how to extract a multiple json objects within objects

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

android java.lang.string cannot be converted to jsonarray

I've been searching through the Internet for a while, still have no idea what should I do... here's my code:
String res = "...";
JSONArray jArr = new JSONArray(res);
res contains following:
[["000000000001","club1","www.example.com","some adress"],["000000000002","club2","www.example.com","some adress2"]]
I just keep getting this error and don't know how to fix it, please help :C
I tried your code and its working fine. Here is the code I tried :
String res = "[[\"000000000001\",\"club1\",\"www.example.com\",\"some adress\"],[\"000000000002\",\"club2\",\"www.example.com\",\"some adress2\"]]";
try {
jArr = new JSONArray(res);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("Array", "" + jArr.toString());
and here is the output :
[["000000000001","club1","www.example.com","some adress"],["000000000002","club2","www.example.com","some adress2"]]

Convert Json Array to Java Array

I'm trying to convert this JSON string into an array:
{"result":"success","source":"chat","tag":null,"success":{"message":"%message%","time":%time%,"player":"%player%"}}
I would like to output it like this:
<%player%> %message%
I'm very new to java, I came from PHP where you could just do somthing along the lines of:
$result = json_decode($jsonfile, true);
echo "<".$result['success']['player']."> ".$result['success']['message'];
Output: <%player%> %message%
Is there an easy way to do this in java?
I searched for some similar topics but I didn't really understand them. Could someone explain this to me like I'm 5?
Why reinvent the wheel, use GSON - A Java library that can be used to convert Java Objects into their JSON representation and vice-versa
JSON-lib is a good library for JSON in Java.
String jsonString = "{message:'%message%',player:'%player%'}";
JSONObject obj = JSONObject.fromObject(jsonString);
System.out.println("<" + obj.get("message") + ">" + obj.get("player") );
You can also use xStream for doing it which has got a very simple API. Just Google for it.
You can always use the following libraries like:
- Jackson
- GSON
Ok here is the right way to do it Without using any library:
Eg:
JSONArray jarr = api.giveJsonArr();
// giveJsonArr() method is a custom method to give Json Array.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobj = jarr.getJSONObject(i); // Taking each Json Object
String mainText = new String(); // fields to hold extracted data
String provText = new String();
String couText = new String();
String fDatu = new String();
try {
mainText = jobj.getString("Overview"); // Getting the value of fields
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) {
}
try {
String cloText = jobj.getString("ClosingDate");
fDatu = giveMeDate(cloText);
System.out.println(fDatu);
} catch (Exception ex) {
}
}
As you see you have many alternatives. Here is a simple one from json.org where you find lots of other alternatives. The one they supply them selves is simple. Here is your example:
String json = "{\"result\":\"success\",\"source\":\"chat\",\"tag\":null,\"success\":{\"message\":\"%message%\",\"time\":%time%,\"player\":\"%player%\"}}";
JSONObject obj = new JSONObject(json);
JSONObject success = obj.getJSONObject("success");
System.out.println("<" + success.get("player") + "> "
+ success.get("message"));

Categories