i have data
like this:
{
"status": "success",
"message": "Student Statement Report",
"data": {
"data": [{
"id": "45",
"transaction_no": "45",
"transaction_date": "2017-05-25",
"transaction_type": "invoice",
"transaction_amount": "1010.00",
"related_invoice_id": "45",
"balance_amount": "1010.00",
"related_user_id": "436",
"related_user_group": "student",
"description": "",
"created_by": "Principal",
"updated_by": "Principal",
"created_at": "2017-05-25 11:57:39",
"updated_at": "2017-05-25 11:57:39"
}],
"opening_balance": 0,
"dates": ["2017-05-22 00:00:00", "2017-05-28 23:59:59"]
}
}
JSONObject jsonObject = new JSONObject(response);
and i am geeting Json expection error from here
String openingBalance = jsonObject.getString("opening_balance");
"opening_balance": 0,
so, my biggest question is should that zero (value) should be quoted or not?
You have to parse it like this:
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance
If you read the number as an Integer then quotation is not necessary. But if your read it as a String then you have to put quotation.
To read as an Integer you can use getInt("json_key")
& for String getString("json_key").
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance
Related
I am trying to Parse below JSON data to String in Java using (GSON) Library, I am able to parse all JSON fields data except one of the JSON Array. I want to check if it's null/empty then in String variable store null value, if it's not then store the original value.
Input JSON Data:
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 37875,
"issues": [
{
"id": "1190",
"key": "GDS-81",
"fields": {
"issuetype": {
"id": "2170",
"name": "Service Request with Approvals",
"subtask": false
},
"customfield_29805": {
"id": "26",
"name": "Issue - First Response",
"completedCycles": []
}
}
}
]
}
Code that I have done so far,
JsonObject object = (JsonObject) new JsonParser().parse(jsonResponse);
JsonArray issuesArray = object.getAsJsonArray("issues");
for(int i=0; i<issuesArray.size(); i++) {
JsonObject currentissues = (JsonObject) issuesArray.get(i);
String Issue_Id = (String) currentissues.get("id").toString().replace("\"", "");
String Issue_Key = (String) currentissues.get("key").toString().replace("\"", "");
String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
JsonArray completedCyclesArray= customfield.getAsJsonArray("completedCycles");
String Issue_FirstResponseStartTime = (completedCyclesArray.size() > 0) ? completedCyclesArray.getAsString() : "NULL";
}
However when I execute code I get below error on line :JsonObject customfield
java.lang.ClassCastException: com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject
[![UpdatedCode StackTrace][1]][1]
[1]: https://i.stack.imgur.com/2wY0S.jpg
you dont need to explicitly , cast JsonElement to JsonObject instead use getAsJsonArray , Once you get your array, you can iterate through all the elements of it.
You also need to handle null check for completedCyclesArray before checking its siz else it will give you the NPE , I have fixed that as well.
Please find the modified working code as below
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonResponse).getAsJsonArray();
for(JsonElement e : array) {
JsonObject currentissues = (JsonObject) e;
String Issue_Id = (String) currentissues.get("id").toString().replace("\"", "");
String Issue_Key = (String) currentissues.get("key").toString().replace("\"", "");
String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
JsonArray completedCyclesArray= customfield.getAsJsonArray("completedCycles");
String Issue_FirstResponseStartTime = (null != completedCyclesArray && completedCyclesArray.size() > 0) ? completedCyclesArray.getAsString() : "NULL";
}
}
Please find my working solution for the updated json request(which not an array but nested json request)
JsonObject object = (JsonObject) new JsonParser().parse(jsonResponse);
JsonArray issuesArray = object.getAsJsonArray("issues");
String expand = object.get("expand").toString();
String startAt = object.get("startAt").toString();
String maxResults = object.get("maxResults").toString();
String total = object.get("total").toString();
System.out.println(String.format("expand %s , startAt %s, maxResults %s, total %s", expand, startAt, maxResults, total));
IntStream.range(0, issuesArray.size()).mapToObj(i -> (JsonObject) issuesArray.get(i)).forEach(currentissues -> {
String Issue_Id = (String) currentissues.get("id").toString().replace("\"", "");
String Issue_Key = (String) currentissues.get("key").toString().replace("\"", "");
String Issue_Type = (String) currentissues.get("fields").getAsJsonObject().get("issuetype").getAsJsonObject().get("name").getAsString();
JsonObject customfield = (JsonObject) currentissues.get("fields").getAsJsonObject().get("customfield_29805");
JsonArray completedCyclesArray = customfield.getAsJsonArray("completedCycles");
String Issue_FirstResponseStartTime = (completedCyclesArray.size() > 0) ? completedCyclesArray.toString() : "NULL";
System.out.println(String.format("Issue_Id %s , Issue_Key %s, Issue_Type %s, Issue_FirstResponseStartTime %s", Issue_Id, Issue_Key, Issue_Type, Issue_FirstResponseStartTime));
});
and this is the output I got :
expand "schema,names" , startAt 0, maxResults 50, total 37875 Issue_Id
1190 , Issue_Key GDS-81, Issue_Type Service Request with Approvals,
Issue_FirstResponseStartTime NULL
Please see my complete working code here complete code
for both the secnarios
Empty completedCycles
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 37875,
"issues": [
{
"id": "1190",
"key": "GDS-81",
"fields": {
"issuetype": {
"id": "2170",
"name": "Service Request with Approvals",
"subtask": false
},
"customfield_29805": {
"id": "26",
"name": "Issue - First Response",
"completedCycles": []
}
}
}
]
}
Non Empty completedCycles
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 37875,
"issues": [
{
"id": "1190",
"key": "GDS-81",
"fields": {
"issuetype": {
"id": "2170",
"name": "Service Request with Approvals",
"subtask": false
},
"customfield_29805": {
"id": "26",
"name": "Issue - First Response",
"completedCycles": [{"name":"abc"},{"name": "xyz"}]
}
}
}
]
}
Try adding getAsJsonObject() at the end of that statement.
I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests
I want output json, but I have error
06-02 23:10:26.110: W/System.err(23235): org.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject
06-02 23:10:26.116: W/System.err(23235): at org.json.JSON.typeMismatch(JSON.java:111)
06-02 23:10:26.117: W/System.err(23235): at org.json.JSONObject.<init>(JSONObject.java:158)
06-02 23:10:26.117: W/System.err(23235): at org.json.JSONObject.<init>(JSONObject.java:171)
I create my code whith example, its my json:
{
"status": "success",
"data": {
"users_information": [
{
"id": "1",
"active": "1",
},
{
"id": "2",
"active": "1",
}]}}
It's my code:
JSONObject data = new JSONObject("data");
JSONArray userInform = data.getJSONArray("users_information");
for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
Log.e("id ", c.getString("id"));
}
String data = "{
"status": "success",
"data": {
"users_information": [
{
"id": "1",
"active": "1",
},
{
"id": "2",
"active": "1",
}]}}"
parse Json
JSONObject data = new JSONObject(data);
JSONArray userInform = data.getJSONArray("users_information");
for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
Log.e("id ", c.getString("id"));
}
The string data json can be replaced by the JSON received from backend
I dont recommend json deserialization like this. Try using at least Gson library. With it you will can create class with same structure like your json and it will parse in single line.
JSONObject data = new JSONObject("data");
You have to place the JSON String where "data" is placed. "data" is just a string and no json like you posted in your example.
If for any reason "data" is your string reference to your JSON String, then you accidentally added the quotes (") which let android interpret it as a String not a reference to a String.
I have encountered a problem whilst developing my Android application. My problem is that I don't know how to parse JSON code from an URL using GSON. I searched Google and SO for about an hour or so, but nothing worked for me. Everything I found on the internet referred to custom JSON code, not code from an URL. Here is a small sample of the data I have.
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
"price": "3.67",
"address": "3885, Saint-Mary",
"diesel": "0",
"id": "33872",
"lat": "45.492907",
"lng": "-73.740715",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "2.0km"
}
]
}
I am a beginner at JSON/GSON so I need a bit of help. Here is what I have:
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
longitude = rootobj.get("price").getAsString();
latitude = rootobj.get("address").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
I tried a loop to parse the array but that failed miserably. Any help regarding this problem is highly appreciated.
------------------------------EDIT-----------------------------------------------
I am extremely sorry about the incorrrect JSON code. I have updated the code but still cannot figure out the solution.
You JSON is wrong:
"date": "3 hours agp",
"distance": "1.9km"
}
{
"country": "Canada",
To coorect it, you must add a ,
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
Try this, using the basic org.json.JSONObject and org.json.JSONArray it works fine for me...
// This string is the JSON you gave as imput
String json = "{ \"status\": { \"error\": \"NO\", \"code\": 200, \"description\": \"none\", \"message\": \"Request ok\" }, \"geoLocation\": { \"city_id\": \"147\", \"city_long\": \"Saint-Laurent\", \"region_short\": \"QC\", \"region_long\": \"Quebec\", \"country_long\": \"Canada\", \"country_id\": \"43\", \"region_id\": \"35\" }, \"stations\": [ {\"country\": \"Canada\",\"price\": \"3.65\",\"address\": \"3885, Boulevard Saint-Rose\",\"diesel\": \"0\",\"id\": \"33862\",\"lat\": \"45.492367\",\"lng\": \"-73.710915\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"1.9km\" }, {\"country\": \"Canada\",\"price\": \"3.67\",\"address\": \"3885, Saint-Mary\",\"diesel\": \"0\",\"id\": \"33872\",\"lat\": \"45.492907\",\"lng\": \"-73.740715\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"2.0km\" } ]}";
try{
JSONObject rootobj = new JSONObject(json);
JSONArray array = rootobj.getJSONArray("stations");
for( int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
String price = o.getString("price");
String address = o.getString("address");
//...
}
}catch(JSONException jse){
// Manage Exception here
}
Try below code to fetch data from url and parse the response using Gson.
Note : Remove "?callback=?" from your url, that will remove "?(" from your response
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json";
URL u = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) u.openConnection();
request.setRequestMethod("GET");
request.connect();
int status = request.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
JsonElement element = new Gson().fromJson (br, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
JsonArray jArray = jsonObj.get("stations").getAsJsonArray();
for (int i = 0, size = jArray.length(); i < size; i++) {
JSONObject jObj = jArray.getJSONObject(i);
System.out.println(" Price : " + jObj.get("price").toString());
System.out.println(" Address : " + jObj.get("address").toString());
}
}
} catch (MalformedURLException ex) {
// Manage Exception here
} catch (IOException ex) {
// Manage Exception here
}
In my android project, I have the string text which got the following data:
[
{
"admin": true,
"created_at": "2012-10-16T07:26:49Z",
"email": "asdf#gmail.com",
"id": 28,
"language": "fr",
"name": "Marc",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
},
{
"admin": false,
"created_at": "2013-04-02T18:47:36Z",
"email": "asdf2#gmail.com",
"id": 263,
"language": "en",
"name": "Marcus",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
}
]
I converted it into a json object thanks to this:
JSONObject jsonObj = new JSONObject(text);
I want to parse that Json object, and setting it inside a ListView, but even with the official documentation I can't succeed in doing so.
After parsing, I want to keep only the first part of the array, and delete every field excepting the email, language and name, to get this in the end:
[
{
"email": "asdf#gmail.com",
"language": "fr",
"name": "Marc"
}
]
You're dealing with a JSONArray - the [ ] - that contains two separate JSONObject. The way you extract values from this structure is simply to go piece by piece, first getting the nested objects from the array and then extracting their internal values. You can then repackage it as you wish. For example:
int numObject = jsonArray.length();
JSONArray repackArray = new JSONArray();
for(int i = 0; i < numObject; i++){
JSONObject nested = jsonArray.getJsonObject(i);
//get values you need
String email = nested.getString("email");
String language = nested.getString("language");
String name = nested.getString("name");
//add values to new object
JSONObject repack = new JSONObject();
repack.put("email", email);
repack.put("language", language);
repack.name("name", name);
//add to new array
repackArray.put(repack);
}
Alternatively if put doesn't work for you, you can always create your own String in JSON format and then simply create a new JSONObject using that string as an argument in the constructor. I assumed you were working with a JSONArray in the above example. If you're starting with a JSONObject the process is the same. Just get the JSONArray out of the object first before unpacking.