I want to parse the ID of the artist "Justin Timberlake" from this nested JSON, but it's driving crazy, i have tried many ways and many examples on here but it still doesn't display the id on my test app. By the way, i am not very experienced.
Here is the JSON:
{
"resultsPage": {
"status": "ok",
"results": {
"artist": [
{
"onTourUntil": null,
"identifier": [
{...}
],
"uri": "http://www.songkick.com/artists/209003-justin-timberlake?utm_source=31833&utm_medium=partner",
"id": 209003,
"displayName": "Justin Timberlake"
},
{
"identifier": [
],
"uri": "http://www.songkick.com/artists/7570864-justin-timberlake-at-united-center?utm_source=31833&utm_medium=partner",
"displayName": "Justin Timberlake at United Center",
"id": 7570864,
"onTourUntil": null
},
{
"onTourUntil": null,
"displayName": "Broadway Sings Justin Timberlake",
"identifier": [
],
"uri": "http://www.songkick.com/artists/8106393-broadway-sings-justin-timberlake?utm_source=31833&utm_medium=partner",
"id": 8106393
},
{
"onTourUntil": null,
"identifier": [
],
"uri": "http://www.songkick.com/artists/7859354-justin-timberlake-and-jay-z-tribut?utm_source=31833&utm_medium=partner",
"displayName": "Justin Timberlake & Jay Z Tribut",
"id": 7859354
}
]
},
"perPage": 50,
"page": 1,
"totalEntries": 4
}
}
And this is my Java:
private void parseJSONResponse(JSONObject response){
if (response == null || response.length()==0){
return;
}
try {
StringBuilder data = new StringBuilder();
JSONArray arrayIds = response.getJSONObject("resultsPage").getJSONObject("results").getJSONArray("artists");
for (int i=0; i<arrayIds.length(); i++){
String currentID= arrayIds.getJSONArray(i).getString(3); //trying to get ID located at position 4.
data.append(currentID+"\n");
}
TextView Id = (TextView) findViewById( R.id.artist );
Id.setText(data.toString());
}catch (JSONException e){
}
}
Since this JSON shows other irrelevant information about artist, and i only want the ID of displayName: "Justin Timberlake", would I need to put an if statement like this:
for (int i=0; i<arrayIds.length(); i++) {
if (arrayIds.getJSONObject(i).equals("Justin Timberlake")) {
String currentID = arrayIds.getJSONArray(i).getString(3);
//trying to get ID located at position 4.
TextView Id = (TextView) findViewById(R.id.artist);
Id.setText(data.toString());
}
}
This works:
Edited:
String json = "{\n" +
"\"resultsPage\": {\n" +
"\"status\": \"ok\",\n" +
"\"results\": {\n" +
" \"artist\": [\n" +
" {\n" +
" \"onTourUntil\": null,\n" +
" \"identifier\": [\n" +
// " {...}\n" +
" ],\n" +
" \"uri\": \"http://www.songkick.com/artists/209003-justin-timberlake?utm_source=31833&utm_medium=partner\",\n" +
" \"id\": 209003,\n" +
" \"displayName\": \"Justin Timberlake\"\n" +
" },\n" +
" {\n" +
" \"identifier\": [\n" +
"\n" +
" ],\n" +
" \"uri\": \"http://www.songkick.com/artists/7570864-justin-timberlake-at-united-center?utm_source=31833&utm_medium=partner\",\n" +
" \"displayName\": \"Justin Timberlake at United Center\",\n" +
" \"id\": 7570864,\n" +
" \"onTourUntil\": null\n" +
" },\n" +
" {\n" +
" \"onTourUntil\": null,\n" +
" \"displayName\": \"Broadway Sings Justin Timberlake\",\n" +
" \"identifier\": [\n" +
"\n" +
" ],\n" +
" \"uri\": \"http://www.songkick.com/artists/8106393-broadway-sings-justin-timberlake?utm_source=31833&utm_medium=partner\",\n" +
" \"id\": 8106393\n" +
" },\n" +
" {\n" +
" \"onTourUntil\": null,\n" +
" \"identifier\": [\n" +
"\n" +
" ],\n" +
" \"uri\": \"http://www.songkick.com/artists/7859354-justin-timberlake-and-jay-z-tribut?utm_source=31833&utm_medium=partner\",\n" +
" \"displayName\": \"Justin Timberlake & Jay Z Tribut\",\n" +
" \"id\": 7859354\n" +
" }\n" +
" ]\n" +
"},\n" +
"\"perPage\": 50,\n" +
"\"page\": 1,\n" +
"\"totalEntries\": 4\n" +
"}\n" +
"}";
try {
JSONObject jsonRootObject = new JSONObject(json);
JSONObject resultsPager = jsonRootObject.getJSONObject("resultsPage");
JSONObject results = resultsPager.getJSONObject("results");
JSONArray artist = results.getJSONArray("artist");
for(int i=0; i < artist.length(); i++){
JSONObject jsonObject = artist.getJSONObject(i);
if(jsonObject.getString("displayName").equals("Justin Timberlake")){
Log.d("json"," ->> Justin Timberlake");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Your code:
private void parseJSONResponse(JSONObject response){
if (response == null || response.length()==0){
return;
}
try {
StringBuilder data = new StringBuilder();
JSONObject resultsPager = response.getJSONObject("resultsPage");
JSONObject results = resultsPager.getJSONObject("results");
JSONArray artist = results.getJSONArray("artist");
for(int i=0; i < artist.length(); i++){
JSONObject jsonObject = artist.getJSONObject(i);
if(jsonObject.getString("displayName").equals("Justin Timberlake")){
Log.d("json"," ->> Justin Timberlake");
}
}
}catch (JSONException e){
}
}
Related
I want to get the name of the status from JSON data.
{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "3876562",
"self": "https://jira2.abc.com/rest/api/2/issue/3876562",
"key": "DEVACDMY-35289",
"fields": {
"status": {
"self": "https://jira2.abc.com/rest/api/2/status/3",
"description": "",
"iconUrl": "https://jira2.abc.com/images/icons/statuses/inprogress.png",
"name": "In Progress",
"id": "3",
"statusCategory": {
"self": "https://jira2.abc.com/rest/api/2/statuscategory/4",
"id": 4,
"key": "indeterminate",
"colorName": "yellow",
"name": "In Progress"
}
}
}
}
I try this but it doesn't work.
Map address = ((Map)jo.get("fields"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
Map status=((Map)jo.get(pair.key);
Iterator<Map.Entry> itr2 =status.entrySet().iterator(); while(itr2.hasNext())
{
itr1=((Map)itr2.next()).entrySet().iterator();
while(itr1.hasNext())
{
Map.Entry pair=itr1.next();
System.out.println(pair.getKey()+":"+pair.getValue());
}}
Looking at the json, it is not an array, it is simply a JsonObject and to get the string of the status name you need to traverse the same way.
To get the status name there is a hierarchy that you need to follow
JSONObject --> fields*(this is again a JSONObject)* --> status*(this is
again a JSON object)* -> name (this is string)
Look at the following code
String str = "{\n" +
" \"expand\": \"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations\",\n" +
" \"id\": \"3876562\",\n" +
" \"self\": \"https://jira2.abc.com/rest/api/2/issue/3876562\",\n" +
" \"key\": \"DEVACDMY-35289\",\n" +
" \"fields\": {\n" +
" \"status\": {\n" +
" \"self\": \"https://jira2.abc.com/rest/api/2/status/3\",\n" +
" \"description\": \"\",\n" +
" \"iconUrl\": \"https://jira2.abc.com/images/icons/statuses/inprogress.png\",\n" +
" \"name\": \"In Progress\",\n" +
" \"id\": \"3\",\n" +
" \"statusCategory\": {\n" +
" \"self\": \"https://jira2.abc.com/rest/api/2/statuscategory/4\",\n" +
" \"id\": 4,\n" +
" \"key\": \"indeterminate\",\n" +
" \"colorName\": \"yellow\",\n" +
" \"name\": \"In Progress\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
JSONObject jsonarray = new JSONObject(str);
JSONObject fields = jsonarray.getJSONObject("fields");
JSONObject status = fields.getJSONObject("status");
String name = status.getString("name");
System.out.println("fields : " + fields);
System.out.println("status : " + status);
System.out.println("name: " + name);
output :-
fields : {"status":{"name":"In Progress","self":"https://jira2.abc.com/rest/api/2/status/3","description":"","iconUrl":"https://jira2.abc.com/images/icons/statuses/inprogress.png","id":"3","statusCategory":{"colorName":"yellow","name":"In Progress","self":"https://jira2.abc.com/rest/api/2/statuscategory/4","id":4,"key":"indeterminate"}}}
status : {"name":"In Progress","self":"https://jira2.abc.com/rest/api/2/status/3","description":"","iconUrl":"https://jira2.abc.com/images/icons/statuses/inprogress.png","id":"3","statusCategory":{"colorName":"yellow","name":"In Progress","self":"https://jira2.abc.com/rest/api/2/statuscategory/4","id":4,"key":"indeterminate"}}
name: In Progress
I have below json string
{
"folderId":1,
"parentIds":{},
"folderName":null,
"hiddenFlag":true,
"autoExecute":false,
"updatedDate":"2020-10-15T11:40:55.000Z",
"widgetItems":[
{
"width":4,
"property":{
"name":"GRID",
"widgetdef":{
"id":"91209e5a-6468-4912-b35a-ebfe84ac867e",
"name":"GRID",
"Title":{
"type":"TEXT",
"value":""
},
"dimCount":0,
"reportTO":{
"source":{
"sourceId":388
},
"columns":[
{
"id":null,
"function":"SUM",
"operationErrorCode":0,
"totalAllUsingFunction":"Auto"
},
{
"id":null,
"function":"SUM",
"operationErrorCode":0,
"totalAllUsingFunction":"Auto"
}
],
"columnSummaryType":0,
"drilldownDefaultDimension":{
}
},
"splitBar":{
"value":true
},
"isExistingDashboard":true,
"dimensionColumnCount":0
}
}
}
],
"dashboardName":"Second Dashboard",
"dashboardType":1,
"parentFolderId":1,
"dashboardId":90208
}
Am expecting output below json after split..I want to split reportTO object
{
"source": {
"sourceId": 388
},
"columns": [{
"id": null,
"function": "SUM",
"operationErrorCode": 0,
"totalAllUsingFunction": "Auto"
},
{
"id": null,
"function": "SUM",
"operationErrorCode": 0,
"totalAllUsingFunction": "Auto"
}
],
"columnSummaryType": 0,
"drilldownDefaultDimension": {}
}
public static void main(String[] args) throws IOException {
String rootJson = " {\r\n" +
" \"folderId\": 1,\r\n" +
" \"parentIds\": {},\r\n" +
" \"folderName\": null,\r\n" +
" \"hiddenFlag\": true,\r\n" +
" \"autoExecute\": false,\r\n" +
" \"updatedDate\": \"2020-10-15T11:40:55.000Z\",\r\n" +
" \"widgetItems\": [\r\n" +
" { \r\n" +
" \"width\": 4,\r\n" +
" \"property\": {\r\n" +
" \"name\": \"GRID\",\r\n" +
" \"widgetdef\": {\r\n" +
" \"id\": \"91209e5a-6468-4912-b35a-ebfe84ac867e\",\r\n" +
" \"name\": \"GRID\",\r\n" +
" \"Title\": {\r\n" +
" \"type\": \"TEXT\",\r\n" +
" \"value\": \"\"\r\n" +
" }, \r\n" +
" \"dimCount\": 0,\r\n" +
" \"reportTO\": {\r\n" +
" \"source\": {\r\n" +
" \"sourceId\": 388\r\n" +
" },\r\n" +
" \"columns\": [\r\n" +
" {\r\n" +
" \"id\": null, \r\n" +
" \"function\": \"SUM\", \r\n" +
" \"operationErrorCode\": 0,\r\n" +
" \"totalAllUsingFunction\": \"Auto\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"id\": null, \r\n" +
" \"function\": \"SUM\", \r\n" +
" \"operationErrorCode\": 0,\r\n" +
" \"totalAllUsingFunction\": \"Auto\"\r\n" +
" } \r\n" +
" ], \r\n" +
" \"columnSummaryType\": 0,\r\n" +
" \"drilldownDefaultDimension\": {}\r\n" +
" },\r\n" +
" \"splitBar\": {\r\n" +
" \"value\": true\r\n" +
" }, \r\n" +
" \"isExistingDashboard\": true,\r\n" +
" \"dimensionColumnCount\": 0\r\n" +
" }\r\n" +
" }\r\n" +
" } \r\n" +
" ],\r\n" +
" \"dashboardName\": \"Second Dashboard\",\r\n" +
" \"dashboardType\": 1,\r\n" +
" \"parentFolderId\": 1, \r\n" +
" \"dashboardId\": 90208\r\n" +
"}";
JSONObject jsonObject = new JSONObject(rootJson);
JSONObject reportJson = jsonObject.getJSONArray("widgetItems").getJSONObject(0).
getJSONObject("property").
getJSONObject("widgetdef").
getJSONObject("reportTO");
System.out.println(reportJson);
}
OUTPUT
{
"drilldownDefaultDimension":{
},
"columns":[
{
"function":"SUM",
"totalAllUsingFunction":"Auto",
"id":null,
"operationErrorCode":0
},
{
"function":"SUM",
"totalAllUsingFunction":"Auto",
"id":null,
"operationErrorCode":0
}
],
"columnSummaryType":0,
"source":{
"sourceId":388
}
}
I am getting multiple json objects in a http response.
Eg:
{
"result": {
"Status": "complete",
"id1": "<id1>",
"id2": "<id2>",
"Fields": [{
"fid": "1",
"FName": "<name>"
}, {
"fid": "2",
"FName": "<name>"
}, {
"fid": "3",
"FName": "<name>"
}, {
"fid": "4",
"FName": "<name>"
}]
}
}
The next object is
{
"result": {
"Status": "complete",
"id1": "<id1>",
"id2": "<id2>",
"Fields": [{
"fid": "1",
"FName": "<name>"
}, {
"fid": "2",
"FName": "<name>"
}, {
"fid": "3",
"FName": "<name>"
}, {
"fid": "4",
"FName": "<name>"
}],
"TokenPairs": [{
"Token1": "<token1>",
"Token2": "<token2>",
"FieldMatches": {
"additionalProp1": {
"Score": 0,
"FalseDiscoveryRate": 0
},
"additionalProp2": {
"Score": 0,
"FalseDiscoveryRate": 0
},
"additionalProp3": {
"Score": 0,
"FalseDiscoveryRate": 0
}
}
}]
}
}
I actually want to check the TokenPairs but when I check the jsonPath it picks up the 1st object and returns null. How can I skip the 1st object and go to the second object? I m trying to solve it with adding the response (String) to JsonObject but am getting some errors.
I think I found a solution for you. I would like to provide you the following function which will give you two separate JSON String.
public void JSONSeparator(String JsonString) {
try {
JSONObject object1 = (JSONObject) new JSONTokener(jsonString.replaceAll("\\s+", "")).nextValue();
String firstJson = object1.toString().trim();
String nextJson = jsonString.replaceAll("\\s+", "").substring(firstJson.length());
System.out.println("First JSON String: " + firstJson);
System.out.println("Second JSON String: " + nextJson);
} catch (Exception e) {
e.printStackTrace();
}
}
The idea is to take the first JSON token, and then get the remaining part of the string after you get the first. I used the JSONTokener for picking up the first JSONObject. Then took the length of the object and hence I got the second JSON String using substring method.
The JsonString that I used to pass through this function was the following.
private String jsonString = "{\n" +
" \"result\": {\n" +
" \"Status\": \"complete\",\n" +
" \"id1\": \"<id1>\",\n" +
" \"id2\": \"<id2>\",\n" +
" \"Fields\": [{\n" +
" \"fid\": \"1\",\n" +
" \"FName\": \"<name>\"\n" +
" }, {\n" +
" \"fid\": \"2\",\n" +
" \"FName\": \"<name>\"\n" +
" }, {\n" +
" \"fid\": \"3\",\n" +
" \"FName\": \"<name>\"\n" +
" }, {\n" +
" \"fid\": \"4\",\n" +
" \"FName\": \"<name>\"\n" +
" }]\n" +
" }\n" +
"}" + "{" +
" \"result\": {\n" +
" \"Status\": \"complete\",\n" +
" \"id1\": \"<id1>\",\n" +
" \"id2\": \"<id2>\",\n" +
" \"Fields\": [{\n" +
" \"fid\": \"1\",\n" +
" \"FName\": \"<name>\"\n" +
" }, {\n" +
" \"fid\": \"2\",\n" +
" \"FName\": \"<name>\"\n" +
" }, {\n" +
" \"fid\": \"3\",\n" +
" \"FName\": \"<name>\"\n" +
" }, {\n" +
" \"fid\": \"4\",\n" +
" \"FName\": \"<name>\"\n" +
" }],\n" +
" \"TokenPairs\": [{\n" +
" \"Token1\": \"<token1>\",\n" +
" \"Token2\": \"<token2>\",\n" +
" \"FieldMatches\": {\n" +
" \"additionalProp1\": {\n" +
" \"Score\": 0,\n" +
" \"FalseDiscoveryRate\": 0\n" +
" },\n" +
" \"additionalProp2\": {\n" +
" \"Score\": 0,\n" +
" \"FalseDiscoveryRate\": 0\n" +
" },\n" +
" \"additionalProp3\": {\n" +
" \"Score\": 0,\n" +
" \"FalseDiscoveryRate\": 0\n" +
" }\n" +
" }\n" +
" }]\n" +
" }\n" +
"}";
Please note that, in order to get precise index for the substring, we need to remove all spaces and new lines using the replaceAll function that I had used. Hope that little trick helps you.
I have a json array as below:
[
{
"_id": {
"$oid": "57833bf8cb3099a383e8e2af"
},
"Name": "3GBWS",
"Version": "QV3.2",
"Type": "FQGA",
"SerialNO": "L1D73708884",
"Location": "TEXAS"
},
{
"_id": {
"$oid": "5784818bcb30b4918964b50f"
},
"Name": "3GBTW",
"Version": "WN6.0",
"Type": "FQGW",
"SerialNO": "O1143734584",
"Location": "OHIO"
},
{
"_id": {
"$oid": "5784818bcb30b4918964b50f"
},
"Name": "TEXAS",
"Version": "AS1.0",
"Type": "FWQA",
"SerialNO": "DH783708884",
"Location": "NY"
},
{
"_id": {
"$oid": "5784818bcb30b4918964b50f"
},
"Name": "3GLTS",
"Version": "WE9.0",
"Type": "FQGW",
"SerialNO": "L0943708884",
"Location": "TEXAS"
}
]
My aim is to get output as Texas=2 .
Here I need to get the occurrence of "TEXAS" only under the key "Location".
Is there any way to compare the key-value pair in java? I tried with int location = Collections.frequency(json_string, "TEXAS"); , but this wont consider the key "Location".
Please help.
Since you haven't provided your JSON library I'm assuming org.json.
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String... args) {
String json = "[\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"57833bf8cb3099a383e8e2af\"\r\n" +
" },\r\n" +
" \"Name\": \"3GBWS\",\r\n" +
" \"Version\": \"QV3.2\",\r\n" +
" \"Type\": \"FQGA\",\r\n" +
" \"SerialNO\": \"L1D73708884\",\r\n" +
" \"Location\": \"TEXAS\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"5784818bcb30b4918964b50f\"\r\n" +
" },\r\n" +
" \"Name\": \"3GBTW\",\r\n" +
" \"Version\": \"WN6.0\",\r\n" +
" \"Type\": \"FQGW\",\r\n" +
" \"SerialNO\": \"O1143734584\",\r\n" +
" \"Location\": \"OHIO\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"5784818bcb30b4918964b50f\"\r\n" +
" },\r\n" +
" \"Name\": \"TEXAS\",\r\n" +
" \"Version\": \"AS1.0\",\r\n" +
" \"Type\": \"FWQA\",\r\n" +
" \"SerialNO\": \"DH783708884\",\r\n" +
" \"Location\": \"NY\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"5784818bcb30b4918964b50f\"\r\n" +
" },\r\n" +
" \"Name\": \"3GLTS\",\r\n" +
" \"Version\": \"WE9.0\",\r\n" +
" \"Type\": \"FQGW\",\r\n" +
" \"SerialNO\": \"L0943708884\",\r\n" +
" \"Location\": \"TEXAS\"\r\n" +
" }\r\n" +
"]";
JSONArray array = new JSONArray(json);
int count = 0;
for(int i = 0; i < array.length(); i++) {
JSONObject element = array.getJSONObject(i);
String location = element.getString("Location");
if(location.equals("TEXAS")) {
count ++;
}
}
System.out.println("TEXAS=" + count);
}
}
I'd recommend you generate your POJO classes with an online tool (e.g. http://www.jsonschema2pojo.org/) and then you can simply manipulate them anyway you want. For example with a static method:
public static int countLocationOccurrences(List<YourClass> collections, String location) {
int count = 0;
for(YourClass item : collections) {
if (item.getLocation().equals(location)) {
count++;
}
}
return count;
}
First filter some values:
locations = j.map(elem => elem.Location) // j is the array
after this you well have an array with the locations, and you can do with it as you like.
I am trying to Parse this JSON
{
"details": {
"Service Tax": [
{
"tax_order": 3,
"inclusive": [
{
"Discount": 1,
"Service Charge": 1
}
]
}
],
"VAT": [
{
"tax_order": 3,
"inclusive": [
{
"Discount": 1,
"Service Charge": 1,
"Item": 1
}
]
}
]
},
"vendor_id": 1
}
Is it possible to extract the fields for that value present in the array .
For example if it is Service Tax , i need to fetch the Discount and Service Charge
For example if it is VAT , i need to fetch the Discount , Service Charge and Item
package test;
import org.json.JSONArray;
import org.json.JSONObject;
public class Tester {
public static void main(String args[]) throws Exception
{
String json = "{\r\n" +
" \"details\": {\r\n" +
" \"Service Tax\": [\r\n" +
" {\r\n" +
" \"tax_order\": 3,\r\n" +
" \"inclusive\": [\r\n" +
" {\r\n" +
" \"Discount\": 1,\r\n" +
" \"Service Charge\": 1\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ],\r\n" +
" \"VAT\": [\r\n" +
" {\r\n" +
" \"tax_order\": 3,\r\n" +
" \"inclusive\": [\r\n" +
" {\r\n" +
" \"Discount\": 1,\r\n" +
" \"Service Charge\": 1,\r\n" +
" \"Item\": 1\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ]\r\n" +
" },\r\n" +
" \"vendor_id\": 1\r\n" +
"}";
String[] json_order = new String[]{"Service Tax", "VAT"};
JSONObject inputRqstJson = new JSONObject(json);
JSONObject details_json = inputRqstJson.getJSONObject("details");
for(String tax_name : json_order)
{
JSONArray tax_nameJarray = details_json.getJSONArray(tax_name);
System.out.println(tax_nameJarray);
}
}
}