Java: Json has key/field - java

I'd like to know the most simple way to detect if a key/field exists in a JSON String.
for example:
if(jsonObject(myJsonString).hasKey("myKey")){
}
I would not prefer to write a lot. I am currently using minimal JSON and it appears it does not have such a function.
Answer:
JSONObject jsonObj2 = new JSONObject(message);
if(jsonObj2.has("key"));

Not sure what you mean exactly by minimal JSON, personally I find the org.json package simple and straightforward (i.e. minimal overhead). It is found here. The org.json.JSONObject class, for example, contains the public boolean has(String key) method, which is used to check if a certain key exists.

In minimal-json, you'd write:
if (JsonObject.readFrom(myJsonString).get("myKey") != null) {
...
}

I faced the same problem.
obj.has("myKey") was not working for minimalJson.
My solution:
Take your JsonObject obj which has that key and then do the following:
if(obj.get("myKey") != null)

Related

Why JSONObject converts stringified array to JSONArray on put operation? How to stop this?

When I tried to put stringified array in JSONObject, it became a JSONArray. But I want to keep the stringified array. Any help will be appreciated.
eg:
JSONObject jsonObj = new JSONOject();
jsonObj.put("stringified_array", "[1,2]");
So, when I debugged it, the jsonObj properties were
key : "stringified_array", value : [1,2] (JSONArray)
Edit:
Here is the link for sample code: https://onlinegdb.com/UbV6VXvpJ.
Code won't compile due to missing packages in online ide, just for better understanding of scenario I have added the link.
Here is why, if you look at the declaraction of constructor of JSONObject, you will find what you are looking for. One of the constructor of JSONObject class looks like following:
public org.json.JSONObject put(java.lang.String key, java.util.Map<?,?> value) throws org.json.JSONException { /* compiled code */ }
If you know how to do reverse engineering, you should be able to find more about the actual implementation :)!
Hopefully, this will help you out!

How to invoke a method on Optional in minimal scenario

I have Json which can look like this:
{
"workshop_name" : "ABC"
"user_name" : "DEF"
}
In my app workshop_name is not mandatory, so it can came in minimal version:
{
"user_name" : "DEF"
}
Now I was thinking about using Java8 Optional to get workshop_name from JSON. I was using org.json library and JSONObject. I could easily check optional like this:
public static EnrichContext createEnricher(JSONObject json) {
EnrichContext enrichContext = new EnrichContext();
enrichContext.setWorkshopName(Optional.ofNullable(json.getString("workshop_name")).orElse("DEFAULT"));
enrichContext.setUserName(json.getString("user_name"));
}
I was forced to switch to GSON where it looks a little bit different.
json.get("workshop_name").getAsString();
This means that I have a new object in the middle after calling get on JsonObject (from GSON).
I tried to use nested Optional check, but it looks just too complex.
What I figured out is:
enrichContext.setWorkshopName((Optional.ofNullable(json.get("workshop_name")).orElse(new JsonPrimitive("DEFAULT"))).getAsString());
I don't like an idea of creating new JsonPrimitive on every read. Is there more optimal way for that issue?
What you could do is use a Optional<String> instead of a Optional<JsonPrimitive>
String workshopName = Optional.ofNullable(json.get("workshop_name"))
.map(JsonElement::getAsString)
.orElse("DEFAULT");

how to know if a json object contains a json object

I am a novice in java and I am looking for a way to know if a json object contains another jsonObject by using json.org library (not json.org.simple).
For the moment I am using this :
JSONObject json= new JSONObject();
json.has("JsonFieldName");
but but I need to know if there is a way to not specify the Json field Name
If you have a better solution with Json.org, I will take.
Thanks
You can get an Iterator for all the keys in the object from keys, and loop through them seeing if any of the values for the keys is a JSONObject (as opposed to a JSONArray or primitive).
for (String key : json.keys()) {
if (json.get(key) instanceof JSONObject) {
// Yes, it contains at least one JSONObject, whose key is `key`
}
}

How to parse a jsonObject or Array in Java

I have an API request from my CRM that can either return a jsonObject if there is only one result, or a jsonArray if there are multiple results. Here are what they look like in JSON Viewer
JsonObject:
JsonArray:
Before you answer, this is not my design, it's my CRM's design, I don't have any control over it, and yes, I don't like how it is designed either. The only reason I am not storing the records in my own database and just parsing that, which would be MUCH easier, is because my account is having issues not running some workflows that would allow me to auto add the records. Is there any way to figure out if the result is an object or an array using java? This is for an android app by the way, I need it to display the records on the phone.
You should use OPT command instead of GET
JSONObject potentialObject=response.getJsonObject("resuslt")
.getJsonObject("Potentials");
// here use opt. if the object is null, it means its not the type you specified
JSONObject row=potentialObject.optJsonObject("row");
if(row==null){
// row is json array .
JSONArray rowArray=potentialObject.getJsonArray("row");
// do whatever you like with rowArray
} else {
// row is json object. do whatever you like with it
}
ONE
You can use instanceof keyword to check the instances as in
if(json instanceof JSONObject){
System.out.println("object");
}else
System.out.println("array");
TWO
BUT I think a better way to do this is choose to use only JSONArray so that the format of your results can be predicated and catered for. JSONArrays can contain JSONObjects. That is they can cover the scope of JSONObject.
For example when you get the response (either in a JSONObject or a JSONArray), you need to store that in an instance. What instance are you going to store it in? So to avoid issues use JSONArray to store the response and provide statements to handle that.
THREE
Also you can try method overloading in java or Generics
Simplest way is to use Moshi, so that you dont have to parse, even in the case of the Model changing later, you have to change your pojo and it will work.
Here is the snippet from readme
String json = ...;
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);
BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);
https://github.com/square/moshi/blob/master/README.md

Extract just one line from a big JSON in Java

Since my very first days of Java + JSON I tried to extract just some certain parts of a JSON.
But no matter if which of the libraries I used:
Gson
json-simple
javax.json
it never was possible to make it quick and comfortable. Mostly for easy task or even prototyping. It already cost me many hours of different approaches.
Going trough the hierarchy of an JSON
Object jsonObject = gson.fromJson(output, Object.class);
JsonElement jsonTree = gson.toJsonTree(jsonObject);
JsonArray commitList = jsonTree.getAsJsonArray();
JsonElement firstElement = commitList.get(0);
JsonObject firstElementObj = firstElement.getAsJsonObject();
System.out.println(firstElementObj.get("sha"));
JsonElement fileList = firstElementObj.get("files");
This is dirty code for a reason. It shows how many early approaches looks like and how many people cannot achieve it to do it better early.
Deserializing JSON to a Java Object
Your have to analyse the complete JSON to create an complete Java-Object representation just to get access to some single memebers of it. This is a way I never wanted to do for prototyping
JSON is an easy format. But using libraries like that is quite difficult and often an problem for beginner. I've found several different answers via Google and even StackOverflow. But most were quite big larged which required to create a own specific class for the whole JSON-Object.
What is the best approach to make it more beginner-friendly?
or
What is the best beginner-friendly approach?
Using Jackson (which you tagged), you can use JsonPointer expressions to navigate through a tree object:
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper
.readTree("[ { \"sha\": \"foo\", \"files\": [ { \"sha\": \"bar\" }, { \"sha\": \"quux\" } ] } ]");
System.out.println(tree.at("/0/sha").asText());
for (JsonNode file : tree.at("/0/files")) {
System.out.println(file.get("sha").asText());
}
You could also use the ObjectMapper to convert just parts of a tree to your model objects, if you want to start using that:
for (JsonNode fileNode : tree.at("/0/files")) {
FileInfo fileInfo = mapper.convertValue(fileNode, FileInfo.class);
System.out.println(fileInfo.sha);
}
If your target class (FileInfo) specifies to ignore unknown properties (annotate target class with #JsonIgnoreProperties(ignoreUnknown = true) or disable DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES on the mapper), then you can simply declare the properties you are interested in.
"Best" is whatever works to get you going.
Generate Plain Old Java Objects from JSON or JSON-Schema
One little helper I found via my research was an Online-Tool like
http://www.jsonschema2pojo.org/
This is a little help, when you know about that. But the negative side I mentioned at point 2 is still there.
You can use JsonSurfer to selectively extract value or object from big json with streaming JsonPath processor.
JsonSurfer jsonSurfer = JsonSurfer.gson();
System.out.println(jsonSurfer.collectOne(json, "$[0].sha"));
System.out.println(jsonSurfer.collectOne(json, "$[0].files"));

Categories

Resources