JSON File / Android - Get the value of string - java

I have the following JSON file format :
{"code":200,
"status":"OK",
"data":[
{"timings":
{"Fajr":"03:11 (EET)",
"Sunrise":"04:54 (EET)",
"Dhuhr":"11:53 (EET)",
"Asr":"15:29 (EET)",
"Sunset":"18:52 (EET)",
"Maghrib":"18:52 (EET)",
"Isha":"20:23 (EET)",
"Imsak":"03:01 (EET)",
"Midnight":"23:53 (EET)"},....
I want to get the value of Asr (for example) & parse it into string variable, I tried the below but nothing works (Please note: response is successfully retrieved, so no issue with reaching the JSON file, but only to get the value of string).
String mfajr = response1.getJSONArray("data").getJSONObject(0)
.get("Fajr").toString();
String mdoher = response1.getJSONArray("data").getJSONObject(0)
.getJSONArray("timings")
.get(Integer.parseInt("Dhuhr")).toString();

Assuming that response1 is a JSONObject.
String mfajr = response1.getJSONArray("data")
.getJSONObject(0)
.get("Fajr").toString();
That will fail because getJSONObject(0) returns an object that has a "timings" attribute ... not a "Fajr" attribute.
String mdoher = response1.getJSONArray("data")
.getJSONObject(0).getJSONArray("timings")
.get(Integer.parseInt("Dhuhr")).toString();
That will fail because the value of "timings" attribute is JSON object, not a JSON array.
Also, the value of the "Dhuhr" attribute is not an integer, so parseInt is not going to work. If you want the value as an integer, you are going to do some string analysis to convert "11:53 (EET)" to an integer.
Basically, you need to make sure that your Java code precisely matches the JSON structure. Close enough is NOT good enough.
OK .... so you want someone to write your code for you.
Try this:
String mfajr = response1.getJSONArray("data")
.getJSONObject(0)
.getJSONObject("timings")
.getString("Fajr");
Now, compare it with the structure of the JSON.

Related

How to convert attribute datatype from String to Array in Couchbase

I have a problem. I want to change the data-type of an attribute from String to Array.
{
“id”: “trn:tarb:tradingpartner:uuid:00000464-fa72-49fe-b050-c4bf1cfd8259”,
“partnerNumber”: “1098981”,
“partnerName”: "AFLO ",
“currencyCode”: “GBP”,
“commercialPartnerStatus”: “Inactive”,
“source”: {
“id”: “STV0001$$”,
“name”: “QS”
},
“corpCode”: “DR”,
“subCorpCode”: “001”,
“targetMarket”: “UK”
}
In the above one, I want to change targetMarket, which is in String currently to Array as below without changing its name.
“targetMarket”:[
“UK”,
“IN”
]
The problem is on the old data which is in string format and if change the attribute in java then I am getting error while retriving data from db. it can't cast from string to arrayList automatically.Because of this I have to change the old data first then I have to change the code in java. If data will be null or removed after changing the object from string to array is also fine for me.

Java/Android JSONArray inside JSONObject returning null

I'm developing an app for android that communicates with a server and receives JSON responses from it. Recently I changed the responses structure to contain more information about the requests.
Initially my responses where just the response from a mysqli_query encoded to JSON by the php function json_encode, and looked like this:
[
{"id":"31","description":"Hello"},
{"id":"32","description":"World"},
]
And to retrieve the objects, I would just create a new JSONArray object by calling my_json_array=new JSONArray(response) and iterate over it.
But now, my new responses contain extra data, like this:
{
"error":false,
"idCode":0,
"message":[
{
"id":"32",
"description":"Hello"
},
{
"id":"31",
"description":"World"
}
]
}
So now, as far as I understand, I need to convert this response to a JSONObject, and then extract the message as a JSONarray object by calling my_json_object.getJSONArray("message");.
I can extract the data from the "error" and the "idCode" fields normally, but when I try to extract the JSONArray from "message" it returns null, and no exceptions are thrown except for the NullPointerException.
I've validated the JSON string here, escaped the characters that could be problematic for java like the double quotes, removed uppercases, written the response as a single line, removed the double quotes surrounding the "id" value, used single quotes instead of double quotes, used harcoded string instead of the response from the server, checked the unicode representation of the string to see if contains any invalid characters (and it looks like it doesn't) and I don't know what else to do. Something to notice: the method toString() on the object returns the string "null", and based on the toString() method of the JSONObjects, it seems like the problem comes from the JSONStringer library, and going deeper on the classes it looks like the exception that there is a nesting problem, but I can't find any problem in my JSON string.
The important part of the code:
public String getResponse(){
web_helper.sendRequest();
//everything fine over here
return web_helper.getResponse();
}
public void printData(){ throws JSONExpection
JSONObject my_json_object=new JSONObject(getResponse());
System.out.println("error: "+my_json_object.getBoolean("error"));
System.out.println("idCode: "+my_json_object.getInt("idCode"));
JSONArray my_json_array=my_json_object.getJSONArray("message");
//not sure if the next part works because my_json_array is null
for(int i=0; i<my_json_array.length(); i++){
JSONObject obj=my_json_array.getJSONObject(i);
System.out.println("id: "+obj.getInt("id"));
System.out.println("description: "+obj.getString("description"));
}
}
Any help is appreciated, thank you in advance!.

Extract value using JSON Path from array

I have Json like this below
{"pd":"{\"e\":{\"h\":{\"ak\":\"120\",\"at\":\"app\"},\"b\":[{\"ts\":1319549658547,\"tz\":-400,\"s\":\"StartUpScreen\",\"et\":8,\"ev\":\"sessionStart\",\"si\":\"19477682-de55-414f-82c9-19bec331dc33\",\"tt\":{\"day\":\"Tuesday\"}},{\"ts\":132,\"tz\":-400,\"s\":\"StartUpScreen\",\"et\":3,\"ev\":\"AutomaticFeedRefresh\",\"si\":\"19477682-de55-414f-82c9-19bec331dc33\",\"tt\":{}},{\"ts\":131,\"tz\":-400,\"s\":\"MainScreen\",\"et\":3,\"ev\":\"MainScreen Event\",\"si\":\"19477682-de55-414f-82c9-19bec331dc33\",\"tt\":{}}],\"tt\":{\"OSV\":\"7.10\"}}}","serverPayload":{"httpHeaders":{"x-bluecoat-via":["35D3468EFF4D5F18"],"content-type":["application\/x-www-form-urlencoded"]},"senderIp":["101.100.000.100"]}}
I just need the values of ak, b [ts,si and tt[day]] and senderIp.
Now I have 2 questions, how do I extract all 'ts' attributes in 'b' and 'senderIp'. I have used the below code for ak, ts and si. I am not sure how I get 'tt', also while I run this code I get an exception like below
String pd = JsonPath.read(jsonString, "$.pd");
String ak = JsonPath.read(pd, "$e.h.ak");
String ak = JsonPath.read(pd, "$e.h.b[0]");
// String b = JsonPath.read(pd,"$.e.b[0][0]");
// String b = JsonPath.read(pd,"$.e.b[0][5]");
System.out.println("value of ak: "+ak);
Exception in thread "main"
java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to java.lang.String.
$.e.h.b[0] looks like a JavaScript object (with fields including "ts" and "tz"), not a string. So it's reasonable for your JSON parser to treat it as a JSONObject rather than a string. Probably you need to drill down to $.e.h.b[0].ts or whatever field you're interested in. Something like this:
long ts = JsonPath.read(pd, "$e.h.b[0].ts");
I'm assuming it's your second String ak = line which causes the exception. I'm having trouble understanding your other question about the "ts" attributes. Maybe you could format the JSON string for easier reading?

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

How to handle unknown-type json response in java

I'm new to JSON.
I need to receive a response (in form of a String) from a server. That response can be an object like
{"a" : "value", "b" : "value2", ...}
if the request was successful, or a single string like
"ERROR"
on error.
Using org.json.JSONObject, how do I check which one has been returned?
EDIT
I think this could work, but I'm not sure if this is the right way to do it
if(JSONString.equals("\"ERROR\"") {
//handle error
} else {
//parse actual object
}
Where JSONString is a String containing the server response
Could this work?
The string "ERROR" is not valid JSON. Look at the JSONWriter API and you will see there is no way to produce a JSON string like "ERROR".
If you always want to treat the server response as json, you will need to have it return something like { "error" : true } or { error : false }. Your program will then be able to deserialize check the error field.
If you don't have control on the server response, then you will need to test String.equals("ERROR") before deserializing.
Since you can't make the third party service output valid json, before you do json parsing, just do a string comparison to see if the response is "error".
A quoted string is a valid json value in my opinion. The grammar at json.org does not define object or array as special topleve productions, rfc 4627 defines json-text as being an object or array, but a json value can also be a number, string, boolean or null.
From my reading of the org.json javadoc the following should work:
Object value = new JSONTokener(inputString).nextValue();
if (value instanceof String && ((String)value).equals("ERROR")) {
// handle error
} else if (value instanceof JSONObject) {
// handle response data
}
Using the tokener you are not affected by eventual additional whitespace in the response.

Categories