Read below JSON data and fetch status name - java

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

Related

how to convert json to list/map with jackson

I encountered a piece of json as below:
{
"code": 1,
"msg": "query success",
"obj": {
"data": [
{
"name": "",
"value": {
"num": "89"
}
},
{
"name": "1",
"value": {
"num": "19"
}
},
{
"name": "2",
"value": {
"num": "6"
}
}
]
},
"success": true,
"duration": 523
}
I need name and num. How to convert it to a list of java.util.List<HashMap<String, String>> with Jackson?
You can use Jackson ObjectMapper with TypeReference ,
First you need to read it as Map<String,Object> then you can extract the name and num with Java.
you need to get the data from obj then for each item in the dataList you have to map it to a new HashMap as shown below
ObjectMapper objectMapper = new ObjectMapper ();
Map<String,Object> jsonMap = objectMapper.readValue(jsonData,new TypeReference<Map<String,Object>>(){});
List<Object> data = ((Map<String,Object>)jsonMap.get("obj")).get("data");
List<Map<String,String> result = data.stream()
.map(d->(Map<String,Object> d)
.map(d->{
Map<String,String> map = new HashMap();
map.put(d.get("name"),((Map<String,String>)d.get("value")).get("num"));
return map;
})
.collect(Collectors.toList());
However if you can create a class for the the data it will be bit easier.
Library Josson can do the job.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
"{" +
" \"code\": 1," +
" \"msg\": \"query success\"," +
" \"obj\": {" +
" \"data\": [" +
" {" +
" \"name\": \"\"," +
" \"value\": {" +
" \"num\": \"89\"" +
" }" +
" }," +
" {" +
" \"name\": \"1\"," +
" \"value\": {" +
" \"num\": \"19\"" +
" }" +
" }," +
" {" +
" \"name\": \"2\"," +
" \"value\": {" +
" \"num\": \"6\"" +
" }" +
" }" +
" ]" +
" }," +
" \"success\": true," +
" \"duration\": 523" +
"}");
Transformation
JsonNode node = josson.getNode("obj.data.map(name::value.num)");
System.out.println(node);
List<Map<String, String>> result = Josson.readValueFor(node, List.class);
System.out.println(result);
Output
[{"":"89"},{"1":"19"},{"2":"6"}]
[{=89}, {1=19}, {2=6}]

Json object, convert json array into a json object in java

I have one json array like this
"values":[
{
"locale":"en_US",
"source_key":"book_format",
"value":"Hardback",
"display_attr_name":"Book Format",
"source_value":"Hardback",
"isPrimary":"true"
},
{
"isFacetValue":"true",
"facet_version":"1.1",
"locale":"en_US",
"value":"Hardcover"
}
]
I need to get the only the distinct keys from above json array
{
"locale":"en_US",
"source_key":"book_format",
"value":"Hardback",
"display_attr_name":"Book Format",
"source_value":"Hardback",
"isPrimary":"true",
"isFacetValue":"true",
"facet_version":"1.1"
}
And the output will be in the form of jsonobject.
https://github.com/octomix/josson
Josson josson = Josson.fromJsonString(
"{" +
" \"values\": [" +
" {" +
" \"locale\": \"en_US\"," +
" \"source_key\": \"book_format\"," +
" \"value\": \"Hardback\"," +
" \"display_attr_name\": \"Book Format\"," +
" \"source_value\": \"Hardback\"," +
" \"isPrimary\": \"true\"" +
" }," +
" {" +
" \"isFacetValue\": \"true\"," +
" \"facet_version\": \"1.1\"," +
" \"locale\": \"en_US\"," +
" \"value\": \"Hardcover\"" +
" }" +
" ]" +
"}");
JsonNode node = josson.getNode("values.mergeObjects()");
System.out.println(node.toPrettyString());
Output
{
"locale" : "en_US",
"source_key" : "book_format",
"value" : "Hardcover",
"display_attr_name" : "Book Format",
"source_value" : "Hardback",
"isPrimary" : "true",
"isFacetValue" : "true",
"facet_version" : "1.1"
}

populating nested records with array in Avro using a GenericRecord

I have the following schema:
{
"name": "AgentRecommendationList",
"type": "record",
"fields": [
{
"name": "userid",
"type": "string"
},
{
"name": "friends",
"type": {
"type": "array",
"items": {
"name": "SchoolFriends",
"type": "record",
"fields": [
{
"name": "Name",
"type": "string"
},
{
"name": "phoneNumber",
"type": "string"
},
{
"name": "email",
"type": "string"
}
]
}
}
}
]
}
I'm using GenericRecord, and I want to put in an array of arrays for the SchoolFriends.
val avschema = new RestService(URL).getLatestVersion(name)
val schema = new Schema.Parser().parse(avschema.getSchema)
val record = new GenericData.Record(schema)
I would like to do something like record.put(x)
for that particular schema, you can do it in the following way. I would recommend put your record type SchoolFriends in a different schema, it would make easy to get the schema for the collection elements.
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import java.util.ArrayList;
import java.util.List;
public class PopulateNestedAvroObjects {
public static void main(String [] args ){
String strSchema = "{\n" +
" \"name\": \"AgentRecommendationList\",\n" +
" \"type\": \"record\",\n" +
" \"fields\": [\n" +
" {\n" +
" \"name\": \"userid\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"friends\",\n" +
" \"type\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"name\": \"SchoolFriends\",\n" +
" \"type\": \"record\",\n" +
" \"fields\": [\n" +
" {\n" +
" \"name\": \"Name\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"phoneNumber\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"email\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
Schema schema = new Schema.Parser().parse(strSchema);
GenericRecord record = new GenericData.Record(schema);
record.put("userid", "test user");
Schema childSchema = record.getSchema().getField("friends").schema().getElementType();
List<GenericRecord> friendList = new ArrayList();
GenericRecord friend1 = new GenericData.Record(childSchema);
friend1.put("Name", "1");
friend1.put("phoneNumber", "2");
friend1.put("email", "3");
friendList.add(friend1);
record.put("friends", friendList);
System.out.println(record);
}
}

To get the count of key-value occurrence for JSON in java

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.

Android JSON Nested Parser

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){
}
}

Categories

Resources