How to parse a jsonObject or Array in Java - 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

Related

Getting a JSON Array from JSON Object (SOLVED)

First time having to work with JSON data on my own, even if very simple.
Here is the JSON data I'm working with:
{
"heart" : [92, 108],
"temperature" : [85.08, 85.66],
"conductance" : [4095, 4095]
}
What I'm attempting to do is extract one of the three arrays found within that JSON object, but I'm receiving a JSONException: Not a primitive array: class org.json.JSONArray. Here is a portion of the code that I'm using to extract the array of values associated with "heart":
JSONObject obj = new JSONObject(obtainJSONObject());
JSONArray arr = new JSONArray(obj.getJSONArray("heart")); // This is where the error is occuring
int low = arr.getInt(0);
int high = arr.getInt(1);
I've tried to follow what this solution answered, but can't really make much sense of it: How to Get JSON Array Within JSON Object?
I'm not sure if it has something to do with the way how the JSON data is being formatted? I did check online to see if it was any valid or not at https://jsonformatter.curiousconcept.com/. Any help or insights will be greatly appreciated!

Java, map a json

Here's what I wanna do
I have a json, like:
{
"demoNumber":123,
"demoText":"asdasdasd"
}
and I wanna make a simple String array from it, which should be
["demoNumber","demoText"]
In the app we're making the user can add any type of data, so we can't do data models for everything, that's not an option
I have added json to my Gradle:
dependencies {
implementation 'org.json:json:20180130'
}
But it still can't find the method.
Assuming you have the JSON as a string, this example uses the JSON-java library:
JSONObject jo = new JSONObject(myJsonStr);
Set<String> keys = jo.toMap().keySet();
// You should be able to extract an array from the set of keys
See also https://www.baeldung.com/java-org-json

javax.json: Adding a value to a javax JsonValue

I am trying to add a value to a list of JsonValue. Is it possible to do this?
A bit of background, I am retrieving a Json response from a Rest API, within this Json is a list of Names like this:
{
"Name" : {Name1, Name2, Name3, ...}
}
I need to add another name to list so I can modify names through the Rest API. You are able to perform this task as I have it working in PowerShell, however I can not use PowerShell in the final program.
You can't modify JSONObject as it is immutable.
You might want to explore GSON API to update JSONObject.

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

Converting JSONObject to JSON using GSON

I am having an Java Object which consist many type of variables including a JSONObject.
Whan i debug my object i got the following String for JSONObject:-
{"INCLUSIONS":{"OPTIONS":[{"display":"Complimentary stay for children under 5 without extra bed"}]}}
But when i used:-gson.toJson(JSONObj),I got following
{"myHashMap":{"INCLUSIONS":{"myHashMap":{"OPTIONS":{"myArrayList":[{"myHashMap":{"display":"Complimentary stay for children under 5 without extra bed"}}]}}}}}
Someone please can elaborate why it is converting JSONObject to Map & list ??
Or Any work Around ??
Thanks.
Just use myJsonObj.toString() instead of myJsonObj.toJSON()
Your problem happens because a JSONObject is stored as a HashMap to allow the programmer to reach values with methods based on keys. As example,
String jsonStr = "{'key': 'value'}";
JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
String value = json.get("key").getAsString();
You can figure that json attributes are stored as a HashMap<JsonElement>

Categories

Resources