Getting a JSON Array from JSON Object (SOLVED) - java

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!

Related

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

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>

extracting name and id from json

I want to extract id value from this json data. I tried many ways but I don't know what went wrong in my code also I wnt to store id into an array
JSONObject json = readurl("https://graph.facebook.com/"+s);
System.out.println(json);
String json2=json.getString("likes");
{"data":[
{
"id":"**********",
"name":"skkjghkjhkj"
},
{
"id":"********",
"name":"khkfjhkjf"
}
]
I'm not pretty sure if this is the right answer or maybe I've misread the question, but as said in the question extracting the id from data could be done by:
syso(json2.data[i].id)
i=0 -> n
basically your JSON contains an array in it, so you would access it like any other array!
Source: w3schools Stackoveflow

I would like to see an example web method that passes an array of objects from aspx webservice

im trying to self learn how to consume an aspx web service from android.
In this case im trying to pass an array of objects from a web service.
I would like to take a look at a sample [web method] that passes an array of objects.
and if possible a sample code of how the array passed by the web service is consumed by the android application. (the java code)
Any code posted would be highly appreciated.. Thanks in advance!
You will have to use JSON to get array of objects in Android
so Now, let me start to give step by step demo for parsing the same JSON resoponse:
Step – 1:
create a JSONObject with the received response string:
JSONObject jsonObject = new JSONObject(strJSONResponse);
Step – 2:
Get the main object from the created json object by using getJSONObject() method:
JSONObject object = jsonObject.getJSONObject("FirstObject");
Step – 3:
Now this FirstObject contains 2 strings namely “attr1″,”attr2″ and a object namely “sub”.
So get 2 strings by using getString() method.
String attr1 = object.getString("attr1");
String attr2 = object.getString("attr2");
and get a sub object by using the same getJSONObject() method as we have used above:
JSONObject subObject = object.getJSONObject("sub");
Step – 4:
Now this “sub” sub-object contains 1 array namely “sub1″. So we can get this JSON array by using
getJSONArray() method:
JSONArray subArray = subObject.getJSONArray("sub1");
Now, we just need to process this array same as simple string array:
for(int i=0; i<subArray.length(); i++)
{
strParsedValue+="\n"+subArray.getJSONObject(i).getString("sub1_attr").toString();
}

JSON Parsing problem

Hey,
Im trying to parse the following JSON data:
{"chat":
{"link":
[{"#rel":"next","#ref":"http"}],
"events":
{"link2":
[{"#rel":"next","#ref":"http"}]}
}}
The code that reads the data is (where 'a' is the JSON as String):
JSONObject jsonObject1 = new JSONObject(a);
JSONObject jsonObject = jsonObject1.getJSONObject("chat");
So the structure (at least the way I intended) is:
<chat>
<link>
<events>
<link2>
</events>
</chat<
But, after getJsonObject("chat"), jsonObject equals to:
{"chat":{"events":{"link2":[{"#ref":"http","#rel":"next"}]},"link":[{"#ref":"http","#rel":"next"}]}}
What am I missing? Why does the data flips and the structure changes?
The properties in a JSON object are not sorted. From the JSON site:
An object is an unordered set of name/value pairs...
(My emphasis) Therefore the position of link and event are irrelevant for the parser. Bottom line, link and event are at the same level therefore they can be shifted and wherever order matters use arrays in JSON ... [].

Categories

Resources