I am trying to compare the key of a JSON Object to a String to assess whether or not my JSON Object contains the specified value at that key before continue processing.
Here is a sample of the String .
{'type':'Layout','subType':'REPEATGRID','pgRef':'.pySections(1).pySectionBody(1).pyTable.pyRows(1).pyCells(3).pySections(1)'}
Here is the code I used to perform the evaluation. Let's assume the String above is store in a variable str
jsonString = str.replaceAll("\'", "\"");
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
System.out.println((String) jsonObject.get("subType") == "REPEATGRID");
The code above returns false while the statement System.out.println((String) jsonObject.get("subType")); returns REPEATGRID
Why is the evaluation returning false?
How can I properly evaluate this situation?
PS: I am using org.json.simple library.
try to use equals() instead of ==
System.out.println((String) jsonObject.get("subType").equals("REPEATGRID"));
Further more,to aovid NullPointerException,you can improve as above:
System.out.println("REPEATGRID".equals((String) jsonObject.get("subType")));
Related
I am quite new to Java and trying to understand the effect of using toString() while accessing the individual string elements of JSON object in Java.
Below are the steps followed:
Parse the JSON data. Let's assume only string elements are there in parsed JSON data.
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(json_data);
{
"firstname" : "new",
"lastname" : "human",
"id" : "some_id"
}
Try to access the individual elements.
Access without toString():
Public static String firstname = jsonObj.get("firstname");
Access with toString():
Public static String firstname = jsonObj.get("firstname").toString();
I do not see a difference when I try to print the data.
However I would like to know the difference between the above 2 methods, and also will there be any issues if I use without toString() in this particular case.
Appreciate your help.
Thank you
When you have some Int or other type of data type variables in your model class and you want to parse it into a string so for that we use toString(), it will convert int or any other data variable into a string, in your case here you already have string so no need to change again and again and JSON uses string variables when it comes from backend so that the purpose.
toString() returns string representation of property/object on which this method is called.
Whenever we print an object reference, it invokes the toString() method internally as a result , it is not making difference.
Because you are using Json, there is no difference.
You can use the Option, you like more
Running a Play! app with Scala. I'm doing a request where the response is expected to be a JSON string. When checking the debugger, the JsonElement returns OK with all information as expected. However, the problem is when I try to actually run methods on that JsonElement.
val json = WS.url("http://maps.googleapis.com/maps/api/geocode/json?callback=?&sensor=true&address=%s", startAddress+","+startCity+","+startProvince).get.getJson
val geocoder = json.getAsString
The only error I get back is Unsupported Operation Exception: null and I've tried this on getAsString and getAsJsonObject and getAsJsonPrimitive
Any idea why it's failing on all methods? Thanks.
I had a similar problem and I had to change jsonObject.getAsString() to jsonObject.toString();
Maybe your JsonElement is a JsonNull
What you could do is to first check that it isn't by using json.isJsonNull
Otherwise, try to get its String representation with json.toString
In my case I just needed to get the element as an empty string if it is null, so I wrote a function like this:
private String getNullAsEmptyString(JsonElement jsonElement) {
return jsonElement.isJsonNull() ? "" : jsonElement.getAsString();
}
So instead of
val geocoder = json.getAsString
You can just use this
val geocoder = getNullAsEmptyString(json);
It returns "" if the element is null and the actual string if it is not
To add to #Henry's answer. In the spirit of Kotlins "OrNull" Adding an extension function:
fun JsonElement.asStringOrNull(): String? {
return if (isJsonNull) null else asString
}
The class JsonElement will throw Unsupported Operation Exception for any getAs<Type> method, because it's an abstract class and makes sense that it is implemented in this way.
For some reason the class JsonObject, does not implement the getAs<Type> methods, so any call to one of these methods will throw an exception.
Calling the toString method on a JsonElement object, may solve your issue in certain circumstances, but isn't probably what you want because it returns the json representation as String (e.g. \"value\") in some cases.
I found out that also a JsonPrimitive class exists and it does implement the getAs<Type> methods. So probably the correct way to proceed is something like this:
String input = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(input);
if(jsonTree != null && jsonTree.isJsonObject()) {
JsonObject jsonObject = jsonTree.getAsJsonObject();
value = jsonObject.get("key1").getAsJsonPrimitive().getAsString()
}
PS. I removed all the nullability mgmt part. If you are coding in Java you probably want to manage this in a better way.
see GitHub source code for JsonElement:
https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonElement.java#L178
My sample JSON input is as follows:
"JobName":"Test Job 1",
"events":[
{ "features":[],
"InputHiveTable":"uilog_uiclientlogdata",
"eventColumn":"command",
"name":"edu.apollogrp.classroom.discussion.client.events.CreateDiscussionEvent"
},
Consider the field "InputHiveTable", it could be in all uppercase INPUTHIVETABLE, all lowercase inputhivetable, or a mixture of both as it is now.
Currently, I'm reading the field as follows (in Java):
JSONObject jsonObject = (JSONObject) obj;
JSONArray events = (JSONArray) jsonObject.get("events");
String InputHiveTable = (String)event.get("InputHiveTable");
So my question is how do I search for the field "InputHiveTable" while ignoring the case.
I'm using JSON Simple libraries.
If you have to perform this case-insensitive lookup many times, I'd just write a method to do that lookup:
public Object getIgnoreCase(JSONObject jobj, String key) {
Iterator<String> iter = jobj.keySet().iterator();
while (iter.hasNext()) {
String key1 = iter.next();
if (key1.equalsIgnoreCase(key)) {
return jobj.get(key1);
}
}
return null;
}
You could read the JSONObject into a java string, and call String.toLowerCase on it and store it back into a JSONObject. This will turn the entire case of the string to lower case, so you will have to account for that elsewhere in your logic. After that, you then would just have to do a get call on "inputhivetable".
By no means is it a pretty solution, but it is a potential work around if there is absolutely no other way for you to handle what you're returning as your JSON input.
Given that case-insensitivity can be achieved with TreeMap (i.e. via String.CASE_INSENSITIVE_ORDER comparator), you can probably do the following:
Implement your own MyJSONObject extending TreeMap where its methods will be just calling static methods of JSONObject with the same signatures and all required interfaces as in JSONObject. In default constructor write super(String.CASE_INSENSITIVE_ORDER)
Implement ContainerFactory interface where createObjectContainer will return new instance of MyJSONObject (and createArrayContainer will just return new JSONArray).
To run it with new container MyContainerFactory:
StringReader in = new StringReader(yourJSONString);
JSONParser parser = new JSONParser();
parser.parse(in, yourContainerFactory)
So, I get some JSON values from the server but I don't know if there will be a particular field or not.
So like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
And sometimes, there will be an extra field like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"club":"somevalue"
}
I would like to check if the field named "club" exists so that at parsing I won't get
org.json.JSONException: No value for club
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no
mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also
use optString instead of getString:
Returns the value mapped by name if it exists, coercing it if
necessary. Returns the empty string if no such mapping exists
just before read key check it like before read
JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
//it's contain value to be read operation
}
else
{
//it's not contain key club or isnull so do this operation here
}
isNull function definition
Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL.
official documentation below link for isNull function
http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)
You can use has
public boolean has(String key)
Determine if the JSONObject contains a specific key.
Example
JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs
if (JsonObj.has("address")) {
//Checking address Key Present or not
String get_address = JsonObj .getString("address"); // Present Key
}
else {
//Do Your Staff
}
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
Try this:
let json=yourJson
if(json.hasOwnProperty(yourKey)){
value=json[yourKey]
}
Json has a method called containsKey().
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json");
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();
if frameObj.containsKey("person") {
//Do stuff
}
Try this
if(!jsonObj.isNull("club")){
jsonObj.getString("club");
}
I used hasOwnProperty('club')
var myobj = { "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
};
if ( myobj.hasOwnProperty("club"))
// do something with club (will be false with above data)
var data = myobj.club;
if ( myobj.hasOwnProperty("status"))
// do something with the status field. (will be true with above ..)
var data = myobj.status;
works in all current browsers.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.
So you can directly write if (jsonObject.length() > 0) and do your things.
Happy learning!
You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not
I can't figure out how to determine is an element that lives inside a json array is null. To check if the jsonObject itself is null, you simply use:
jsonObject.isNullObject();
But when the object is an array and I want to check if one of the elements of that array is null, this does not work:
jsonArray.get(i).get("valueThatIsNull") == null;
There is also no isNull method available on elements of an array. How do I check if values inside a jsonarray are null? It might help to know that I am passing over a null object from javascript. Maybe null does not mean the same thing in java when it is passed from javascript in json format, but I have also tried putting parentheses around the null and it still does not work.
I am posting some actual source code to help make this clearer. The jsonObject is a part of the jsonArray and the object has multiple values because it iself is an object.
JSONObject mapItem = jsonArray.getJSONObject(i);
int id = mapItem.has("id") ? mapItem.getInt("id") : -1;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = null;
Date sqlDate = null;
if(mapItem.has("date")) {
String dateStr = mapItem.getString("date");
if(!dateStr.equals("null")) {
date = dateFormat.parse(mapItem.getString("date").substring(0, 10)); //Convert javascript date string to java.
sqlDate = new Date(date.getTime());
}
Try .isNull():
For your example:
if(!mapItem.isNull("date")) {
//Value is not null
}
However, to answer the title of this question, "how to tell if a JSONArray element is null", use .equals()
So, to check if index 1 is null:
if (!jsonArray.get(1).equals(null)) {
//jsonArray[1] is not null
}
I guess json passes null values as strings, so you can't check null as a java element. Instead treat the null value as a string as check this way:
if(!mapItem.getString("date").equals("null")) {
//Value is not null
}
I have updated the code snippet in the original question to a working version.
try JSONArray's method
public boolean isNull (int index)
In fact, it uses "null" string comparing to the content
JSONObject.NULL.equals(this.opt(index));