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

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

Related

Removing key/value pairs from JSON file in a certain range with Java

I feel like I'm really close, but I can't quite figure out how to remove key/val pairs over a certain range in a JSON object entry using Java vs finding specific entries. In addition to possibly bad syntax, is it likely my JSON library jar isn't reading the object types right based on the error message? I configured IntelliJ to read the .jar file under the external library section, so I'm not sure if it's the jar placement or the way I wrote the code (or both)
public static void removeTheFields(Object object) {
if (object instanceof JSONArray) {
JSONArray array = (JSONArray) object;
for (int i = 0; i < array.size(); ++i) removeTheFields(array.get(i));
} else if (object instanceof JSONObject) {
JSONObject json = (JSONObject) object;
JSONArray names = (JSONArray) json.keySet();
if (names == null) return;
for (int i = 3; i < names.size() - 8; ++i) {
String key = names.get(i).toString();
json.remove(key);
}
}
}
}
public static void main(String[] args) {
try {
JSONObject obj = (JSONObject) new JSONParser().parse(new FileReader("edu01.json"));
removeTheFields(obj);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.simple.JSONObject (org.json.simple.JSONArray and org.json.simple.JSONObject are in unnamed module of loader 'app')

JSON Object cannot be converted to JSON Array [duplicate]

This question already has answers here:
org.json.JSONObject cannot be converted to JSONArray in android
(6 answers)
Closed 5 years ago.
I am getting this error when I am trying to convert following JSON response string from the server. I want to process JSONObject or JSONArray depending on the response from the server as most of the time it returns JSONArray.
JSON response from server
jsonString = {"message":"No Results found!","status":"false"}
Java code is as below
try
{
JSONArray jsonArrayResponse = new JSONArray(jsonString);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
if(jsonArrayResponse != null && jsonArrayResponse.length() > 0)
{
getCancelPurchase(jsonArrayResponse.toString());
}
}
}
catch(JSONException e)
{
e.printStackTrace();
}
Error Log:
org.json.JSONException: Value {"message":"No Results found!","status":"false"} of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)
at org.json.JSONArray.<init>(JSONArray.java:108)
Can anybody help me.
Thanks
Based on your comment to answer 1, you can do is
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
Your response {"message":"No Results found!","status":"false"} is not an array. It is an object. Use JSONObject instead of JSONArray in your code.
TIP: Arrays are wrapped in square brackets[ ] and objects are wrapped in curly braces{}.
I fix this issue by writing following code [ courtesy #Optional ]
String jsonString = "{\"message\":\"No Results found!\",\"status\":\"false\"}";
/* String jsonString = "[{\"prodictId\":\"P00001\",\"productName\":\"iPhone 6\"},"
+ "{\"prodictId\":\"P00002\",\"productName\":\"iPhone 6 Plus\"},"
+ "{\"prodictId\":\"P00003\",\"productName\":\"iPhone 7\"}]";
*/
JSONArray jsonArrayResponse;
JSONObject jsonObject;
try {
Object json = new JSONTokener(jsonString).nextValue();
if (json instanceof JSONObject) {
jsonObject = new JSONObject(jsonString);
if (jsonObject != null) {
System.out.println(jsonObject.toString());
}
} else if (json instanceof JSONArray) {
jsonArrayResponse = new JSONArray(jsonString);
if (jsonArrayResponse != null && jsonArrayResponse.length() > 0) {
System.out.println(jsonArrayResponse.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}

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

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

Building a JSONObject in Java without throwing an exception

Is there a way in Java to build a JSONObject without having to deal with an exception? Currently I'm using the default constructor, which however forces me to put try/catch blocks in the code. Since in the rest of the code I'm using the "opt" version of get, checking if the return value is null, is there a way to build the object in the same way? (that is, some kind of constructor that returns null if it can't build the json from a string).
Example:
try {
JSONObject temp = new JSONObject(someString);
} catch (JSONException e) {
e.printStackTrace();
}
What I would like to do:
JSONObject temp = ??????(someString);
if(temp != null) {...}
You need to create the method manually, as any parser will most probably throw one or the other Exception in case of any discrepancy.Try something like this:-
public JSONObject verifyJSON(String inputString){
JSONObject temp;
try {
temp = new JSONObject(inputString);
} catch (JSONException e) {
temp = null;
e.printStackTrace();
}
return temp;
}
Then you can do :-
JSONObject temp = verifyJSON(someString);
if(temp != null) {...}

Categories