Parsing a json file in JAVA - java

I have json file. Now, a field names "refs" isn't available in every array. So, what is procedure to parse this kind of field. Because, when I try to parse the json file, 1st array don't have "refs" field but 2nd array hasn't. That's why it throw Null Pointer exception. I tried with this code
JSONArray jsonArray = new JSONArray(tokener);
for (int index = 0; index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
if(!jsonObject.getString("refs").equalsIgnoreCase(null)){
String refs = jsonObject.getString("refs");
}
}
But, it's not working. What is the way to handle this situation or what is the way to solve that problem. Thank you.

If you are not sure that the key is present, call has to check first.

the problem is in your if statement....
if(!jsonObject.getString("refs").equalsIgnoreCase(null)){
What you should be writing is:
if(!jsonObject.has("refs")){
Hope that helps

Try this
if(jsonObject.has("refs")){
refs = jsonObject.getString("refs");
}

You can do it by just replacing 'if' condition like this, It works for me hope useful to u also.
if(jObj.optString("refs") != null)

Related

JSON Object to generic ParseFile Object, issue

I have run in to an issue, while converting my iOS app to android.
The database is structured such that there are "stations", these stations can have multiple images attached, in the parse database, the images are an array of imagePointers.
When i wanted to get the images out in iOS here is what i did:
stations = object in this case
// Get a single image
if ([[object objectForKey:#"imagePointers"] objectAtIndex:0] != [NSNull null]) {
PFFile *imageFile = [[[object objectForKey:#"imagePointers"] objectAtIndex:0] objectForKey:#"image"];
cell.coverImageView.file = imageFile;
[cell.coverImageView loadInBackground];
}
Its pretty simple, i just lift the imagePointers array and get objectAtIndex0, then i cast it to a parse file.
But i can't do this in android, here is what i have atm:
JSONArray imagePointers = thisStation.getJSONArray("imagePointers");
try {
JSONObject indexImage = imagePointers.getJSONObject(0);
} catch ( Exception e ) {
JSONObject indexImage = null;
}
Here i get the object at index 0 as a JSONObject, i cannot use this in a ParseFile Object, since i need to cast it as a generic type ParseFile.
How do i do this? Or is my approach completely incorrect?
Fixed it by avoiding casting to JSON, apparently there is a getList method
// Get parse Image as index image
ParseObject thisStation = stationItems.get(position);
List<ParseObject>imagePointers = thisStation.getList("imagePointers");
ParseFile image = imagePointers.get(0).getParseFile("image");
thumbnail.setParseFile(image);
thumbnail.loadInBackground();
I had the same issue for almost 2 days but finally I solved it by the getList method!
Now all you gotta do is use getList instead of getJSONObject or getJSONArray or whatever, because when you use them you will not be able to use the getParseFile for any of those believe me.
But instead you can do something like:
val obj = parseObject.getList("listname")
val file = obj[0].getParseFile("image")
Now, I don't remember how the syntex is or so but the key here is to use the getList method if you want to get list of all images you saved in a Back4app Parse JSONArray.
Hope you found it helpful.
Goodluck

Processing: how to check if JSON Objects are bound

Since the Processing forum is down I hope one of you guys can help me out.
I made a Processing sketch that pulls data from an API (test here: http://www.europeana.eu/portal/api/console.html ) in JSON-format and reads some fields of this data for visualization. Everything works fine so far except when there are fields that are not bound to every JSONObject.
This is the code for the retrieval of the data:
JSONObject json;
json = loadJSONObject("data.json"); // loading my JSON file into the object
JSONArray CHOData = json.getJSONArray("items"); // array of the items I want data from
for (int i = 0; i < CHOData.size(); i++) {
JSONObject CHO = CHOData.getJSONObject(i); // get a specific item
JSONArray previewObj = CHO.getJSONArray("edmPreview"); // this field is an array, so I need to store it in a JSONArray object first
String[] previewArray = previewObj.getStringArray(); // here I store it in my actual string array
String preview = previewArray[0]; // I only need the first element
}
As you can see, I want the first string of the "edmPreview" array in the object. When I run the sketch, I get an error: "JSONObject["edmPreview"] not found."
This is of course because not every item has such an object. But how can I test if there is an object with this name in an item? I tried with if(CHO.getJSONObject("edmPreview") != null), but same error. Is there a way to look into the JSONObject and check the data values for something called "edmPreview"? There is no such function explained in the Processing reference.
The JSON file essentially looks as follows:
{
"items": [
{
"id": "someID",
"edmPreview": [
"http://europeanastatic.eu/api/image?uri=someimage.jpg"
],
// some other fields
}, // some other items
]
}
I'm new to this JSON-stuff, so maybe I miss something important... Thanks for the help!
So I found the answer myself, but not in the Processing reference, but in the actual reference for the JSONObject class in Java (http://www.json.org/javadoc/org/json/JSONObject.html). I tried some of the methods there and found that hasKey() (which is actually something I came up with myself, combining the method "has()" with the term "key", pure coincidence) as a boolean value works very well:
String preview = "";
if (CHO.hasKey("edmPreview")) {
JSONArray previewObj = CHO.getJSONArray("edmPreview");
String[] previewArray = previewObj.getStringArray();
preview = previewArray[0];
}
So now I learned that Processing is essentially just Java and sometimes not every method is written in the Reference. :-)

Accessing returned object in Loop

I had a quick question, Right now I have a method that returns a populated DTO object, in another class I am calling that method, and then trying to get access to some of the values that are on the returned Object. I am having trouble figuring out what the syntax should be to accomplish this. It is returning "result". I am currently getting an error:
"Null pointer access: The variable result can only be null at this location"
The DTO that I am returning contains a List and I want to get access to one of the values on that list. Below is my code snippet. Thank you for your help!
for (Integer i = 0; i < array.size(); i++) {
// System.out.println(array.get(i));
GetAccountRewardSummaryRequest request = new GetAccountRewardSummaryRequest();
AccountRewardSummaryDTO result = null;
request.accountKey = new AccountIdDTO(array.get(i));
RewardServicesImpl rewardServicesImpl = new RewardServicesImpl();
rewardServicesImpl.getAccountRewardSummary(request);
// This will return an AccountRewardSummaryDTO, print out and see if it is returning properly
System.out.println(result.rewards.get(6));
// System.out.println(request.accountKey);
}
It's not clear from your question, but I suspect that this:
rewardServicesImpl.getAccountRewardSummary(request);
should be:
result = rewardServicesImpl.getAccountRewardSummary(request);
If you want to use the value returned from a method, you need to do something with it.
Your code would be clearer if you didn't declare the result variable until you needed it though - and there's no point in using Integer here instead of int. Additionally, unless you really can't reuse the service, you might as well create that once:
RewardServices service = new RewardServicesImpl();
for (int i = 0; i < array.size(); i++) {
GetAccountRewardSummaryRequest request = new GetAccountRewardSummaryRequest();
request.accountKey = new AccountIdDTO(array.get(i));
AccountRewardSummaryDTO result = service.getAccountRewardSummary(request);
System.out.println(result.rewards.get(6));
}
Also, as noted, the fact that your variable called array clearly isn't an array variable is confusing.

How to obtain the content from Multi-Level JSON format in JAVA?

For example, a kind of JSON as below:
{ "x":"1","y":"2","z":{"a":"1","b":"2","c":"3"}}
Put this as string in JSONObject argument:
JSONObject jaob=new JSONObject(xxx)
and from method "get("x")" of JSONObject I can obtain the value "1"
jaob.get("x")
But how to get "a" of the second level JSON format "z"???
When I try to obtain by
JSONObject(jaob.get("z").toString()).get("a")
but it doesn't work.
Does any one have the idea?
Any response is appreciated, thanks
jaob.getJSONObject("Z").getString("a")
alternatively, you could use getLong or getString on a.
If you read the javadocs it's pretty easy stuff. The reason yours didn't work is that get returns a java.lang.Object not a JSONObject or JSONArray.
Have you tried
JSONObject jaob = new JSONObject(xxx);
jaob.getJSONArray("z");
//or
jaob.getJSONObject("z");
they both return JSONObject according to JSONObject

Java JSONArray from Javascript JSONArray

I am passing a json object from javascript to a java servlet using ajax.
var jsonObj = JSON.stringify(objArray); //Then I pass it to Java using ajax.
In my Java I am getting the json string from the request, then creating a jsonarray, then looping through that array and i'm getting errors when trying to pull one of the json objects from the array.
String dataObj = request.getParameter("obj");
String sql = request.getParameter("sql");
ArrayList<Object> returnArray = new ArrayList<Object>();
int key;
//Get type of object being passed.
JSONArray jsonArray = JSONArray.fromObject(dataObj);
for(int i=0; i<jsonArray.size(); i++) {
String obj = new Gson().toJson(jsonArray.getJSONObject(i)); //This is where i'm getting an error
String className = getClassName(jsonArray.getJSONObject(i));
Class targetClass = null;
try {
targetClass = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//Create Object
Object data = new Gson().fromJson(obj, targetClass);
I'm posting the relevant code, the for loop isn't closed because the rest of the code is quite long, and this is the part where i'm getting the error.
net.sf.json.JSONException: JSONArray[0] is not a JSONObject.
Here is what the json array looks like when its passed in from javascript. This is a println of the jsonArray object.
[{"number":"(123) 456-7050","type":"Home","contactId":1,"id":16662,"className":"beans.PhoneNumber","position":0}]
With one object in it, this code works. But as soon as I get 2 or more, my error comes up.
[[{"number":"(123) 456-7050","type":"Home","contactId":1,"id":16662,"className":"beans.PhoneNumber","position":1},{"number":"(555) 555-1233","type":"Mobile","contactId":1,"id":16656,"className":"beans.PhoneNumber","position":0},{"number":"(999) 999-9999","type":"Home","contactId":1,"id":16664,"className":"beans.PhoneNumber","position":3},{"number":"(222) 222-2222","type":"Home","contactId":1,"id":16666,"className":"beans.PhoneNumber","position":4}]]
It almost looks like when i'm passing more than one object, it create an array of an array, which could be why its not working. But how do I avoid doing that when i'm passing a jsonarray from javascript? Using just the dataObj I have no access to size or get to loop through it.
[
[
{
"number":"(123) 456-7050","type":"Home",
"contactId":1,
"id":16662,
"className":"beans.PhoneNumber",
"position":1
},
{
"number":"(555) 555-1233",
"type":"Mobile",
"contactId":1,
"id":16656,
"className":"beans.PhoneNumber",
"position":0
},
{
"number":"(999) 999-9999",
"type":"Home",
"contactId":1,
"id":16664,
"className":"beans.PhoneNumber",
"position":3
},
{
"number":"(222) 222-2222",
"type":"Home",
"contactId":1,
"id":16666,
"className":"beans.PhoneNumber",
"position":4
}
]
]
This is not an array of objects. This is an array of arrays of objects. According to your description, you are expecting something like the following to be fed to your Java:
[{"foo":"bar"}, {"bar":"baz"}]
But you are really trying to parse:
[[{"foo":"bar"}, {"bar":"baz"}]]
I am not completely sure, because you have not shared the json that you are trying to parse, but the most probable error you have is just what it says: the first element of the array is not JSONObject. Note that string values, lons and booleans are not JSONObjects. I would suggest you to use the more genereal JSONArray.get and check instance of what class it is. Maybe this can head you to the problem with the json you have. If I got it completely wrong - write back and I will try to help. In such a case it will be still useful to share the results of the proposed experiment.
EDIT:
This is double array -> maybe you using getJSONArray(int index) will help you. as the other answer mentioned - this is array of arrays. Also consider changing the javascript to reduce the level of arrays included.

Categories