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.
Related
My app was working fine but suddenly it start giving me erros JSONException: No value for myRating. I know it's means the value doesn't exist on JSON but i cross check dozens times that myRating exist in JSON i received and i am also able to get other values from same node.
Here is my JSON
{
"status": "SUCCESS",
"uData": [
{
"User_ID": "210",
"First_Name": "Alex ",
"Image": "947d051925ba2014f231f17ffc04db6616645163211632870246.jpg",
"coverPhoto": "1ce295d101204be40363f1e11301ed97d41d8cd98f00b204e9800998ecf8427e16645163211188778355.jpg",
"Gender": "Male",
"login_status": "0",
"myRating": "5.00",
"coverImageID": "354",
"ProfileImageID": "343",
"show_onlineStatus_check": "1",
"verify": "1"
},
{
"User_ID": "4",
"First_Name": "John",
"Image": "cf867d87b655591cbda928287da1ca3616520548151008802.jpg",
"coverPhoto": "0323e6cfa77488abce52aa273e2f5f8e16523048561229563452.jpg",
"Gender": "Female",
"login_status": "0",
"myRating": "5.00",
"distance_check": "1",
"coverImageID": "173",
"ProfileImageID": "174",
"show_onlineStatus_check": "1",
"verify": "2"
}
],
"record": 3,
"uCounter": "50"
}
That's how i am parsing JSON into my app
JSONObject parentArray = new JSONObject(completeJSON);
Log.d(TAG, "Parent Array " + parentArray);
JSONArray jsonArray = parentArray.getJSONArray("uData");
String profileCounter = parentArray.getString("uCounter");
Log.d(TAG, "JSON Array Of UDATA " + jsonArray); // User Data Where I have myRating node
String ImageURL, UserID, Distance, CoverPhoto, myRatings = null;
int Rec_Online_Status;
int distance_check, onlineStatus, verifyProfile;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childObject = jsonArray.getJSONObject(i);
String Fname = childObject.getString("First_Name");
ImageURL = childObject.getString("Image");
CoverPhoto = childObject.getString("coverPhoto");
UserID = childObject.getString("User_ID");
String gender = childObject.getString("Gender");
Rec_Online_Status = childObject.getInt("login_status");
distance_check = Integer.parseInt(childObject.getString("distance_check"));
onlineStatus = Integer.parseInt(childObject.getString("show_onlineStatus_check"));
verifyProfile = Integer.parseInt(childObject.getString("verify"));
boolean testValue = childObject.has("myRating");
Log.d(TAG, "doInBackground: Test Log = "+testValue);// This also return False
myRatings = childObject.getString("myRating");// JSONException: No value for myRating
int profileID = Integer.parseInt(childObject.getString("ProfileImageID"));
int coverID = Integer.parseInt(childObject.getString("coverImageID"));
}
I am really not sure what i am doing wrong and when value exist in same node it should get fetched but as you can see i am getting exception. Can anyone help me out in this. The is required to run app so i am not using has or optString.
I have JSON data and want to extract data of only specific fields in Java and store it in String.
Example,
From issues, key:651, From project name:test, updated, created This details for all records of array issues.
Sample JSON Data:
"issues": [
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "651",
"fields": {
"project": {
"name": "test",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
},
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "321",
"fields": {
"project": {
"name": "test2",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
}
]
Java code that I have tried so far jar used - (gson-2.8.5)
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
JsonObject issues0data = (JsonObject) issues0.get("key");
String issue_key = issues0data.get("issue_key").getAsString();
System.out.println("Value of key is -> " + issue_key); // java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
Updated Code
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues_data = (JsonArray) object.get("issues");
for(int i=0; i<issues_data.size(); i++)
{
JsonObject issues = (JsonObject) issues_data.get(i);
String issues_key = (String) issues.get("key").toString();
String project_name = (String) issues.get("name").toString(); // returns null
}
You can convert to string when you get the value.
Change your code like this see if it helps.
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
String issue_key = (String) issues0.get("key");//<---here
System.out.println("Value of key is -> " + issue_key);
Update
If you want all values just put it inside "for":
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
Update 2
The data "updated" and "created" are not inside "issues" they are inside "fields" to get access to them you need to get them from "fields". You have to go inside level by level to get access to variables:
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
JsonObject fields = (JsonObject) issues.get("fields");
JsonObject project = (JsonObject) issues.get("project");
String project_name = (String) project.get("key");
String fields_updated = (String) fields.get("updated");
String fields_created = (String) fields.get("created");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
You are getting an error because you are casting a JsonPrimitive to JsonObject. So instead of using
JsonObject issues0data = (JsonObject) issues0.get("key");
you should do
String issues0data = issues0.get("key").getAsString();
System.out.println("Value of key is -> " + issues0data);
Here, calling getAsString() will invoke JsonPrimitive.getAsString() method. This will take care if the primitive is boolean/number/string and convert it to string.
I have received a json string like so:
{
"data": [
{
"name": "Order",
"value": "2"
},
{
"name": "Address",
"value": "182"
},
{
"name": "DNS",
"value": "null"
},
{
"name": "SSID",
"value": "work"
},
{
"name": "Protocol",
"value": "0"
},
{
"name": "Key",
"value": ""
},
{
"name": "carrier",
"value": "undefined"
},
{
"name": "SSH",
"value": "1"
},
{
"name": "ntp_addr",
"value": ""
},
{
"name": "Name",
"value": ""
}
]
}
I used stringify on an html response and this is what I have to parse. As you can see, it is pretty redundant; I would much rather { "Order":"2" } than { "name":"Order","value":"2" } ... So an array of name-value pairs, instead of an array of objects.
Is there a way I can dynamically format this response so that it will be easier to parse?
What 'd like is to be able to say:
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
String order = dataObject.getString("Order");
String address = dataObject.getString("Address");
// etc...
}
But the current format makes it almost impossible to parse. I'd need loops within loops.
I'd like to use com.google.gson library. And this response easy to parse with it:
private final JsonParser PARSER = new JsonParser();
public void parse(String jsonString) {
JsonObject dataObject = PARSER.parse(jsonString).getAsJsonObject();
JsonArray dataArray = dataObject.get("data").getAsJsonArray();
dataArray.iterator().forEachRemaining(element -> {
String name = element.getAsJsonObject().get("name").getAsString();
String value = element.getAsJsonObject().get("value").getAsString();
}
}
Or you can simply use TypeAdapters for json deserialization directly in the object.
Something like this should do the trick
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
JSONObject simplifiedDataObject = new JSONObject();
for (int i = 0; i < data.length(); i++) {
JSONObject dataField = data.getJSONObject(i);
simplifiedDataObject.put(dataField.getString("name"), dataField.get("value"));
}
You just iterate over each element in data, use the name field as the field on a new JSONObject and simply retrieve the value using the value key.
I am using gson-2.5 for this. There is a slight difference in the format of these two jsons, where in the first one;
"usethis": [
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
I would have parsed this to get "text" this way, and everything would be ok;
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(listcontents);
JsonObject rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("usethis").getAsJsonArray();
for(int i = 0; i < items.size(); i++) {
JsonObject item = items.get(i).getAsJsonObject();
String thetext = item.get("text").getAsString();
System.out.println("text: " + thetext + "\n");
}
The difference is that in the second one, I have nothing to get as the rootobject unlike in the first where I used "usethis";
[
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
And setting
rootobj.get("usethis").getAsJsonArray();
to
rootobj.get("").getAsJsonArray();
just gives me an error. How would I be able to parse the second json?
JsonElement is just a superclass of JsonArray and JsonObject.
JsonArray items = root.getAsJsonArray();
should do what you want.
I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}