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"
}
Related
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}]
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 am trying to parse Json file which contains duplicate keys in java.I am using the method suggesteed in this answer Parsing a json which contains duplicate keys.
The approach works fine if I hard-code the Json but if I read it from a file,only the last duplicate key is read.Please Help as I want to read the Json from a file.Thanks in advance.
Code:
public class am {
public static void main(String args[]) throws Exception
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("sample.json"));
JSONObject a=JSONObject.fromObject(obj);
JSONObject jsonObject=JSONObject.fromObject("{\n" +
" \"Data\": {\n" +
" \"A\": {\n" +
" \"B\": {\n" +
" \"C\": \"c\",\n" +
" \"D\": {}\n" +
" },\n" +
" \"E\": {\n" +
" \"F\": \"f\"\n" +
" },\n" +
" \"G\": {\n" +
" \"H\": \"h\"\n" +
" }\n" +
" },\"A\": {\n" +
" \"B\": {\n" +
" \"C\": \"x\",\n" +
" \"D\": {}\n" +
" },\n" +
" \"E\": {\n" +
" \"F\": \"y\"\n" +
" },\n" +
" \"G\": {\n" +
" \"H\": \"z\"\n" +
" }\n" +
" },\n" +
"
"\n" +
" }\n" +
"}");
System.out.println("Json objects are:::"+a);
System.out.println("Json objects are:::"+jsonObject);
}
}
Json File:
{
"Data": {
"A": {
"B": {
"C": "c",
"D": {}
},
"E": {
"F": "f"
},
"G": {
"H": "h"
}
},"A": {
"B": {
"C": "x",
"D": {}
},
"E": {
"F": "y"
},
"G": {
"H": "z"
}
},
}
}
Output:
Json objects are:::{"Data":{"A":{"B":{"C":"x","D":{}},"E":{"F":"y"},"G":{"H":"z"}}}}
Json objects are:::{"Data":{"A":[{"B":{"C":"c","D":{}},"E":{"F":"f"},"G":{"H":"h"}},{"B":{"C":"x","D":{}},"E":{"F":"y"},"G":{"H":"z"}}]}}
If you do not have a constraint to use external JSON library than you can use net.sf.json.JSONObject to parse your JSON string, It will accept JSON with the duplicate key. It will retain the duplicated values by storing them into arrays.
JSONObject jsonObject = JSONObject.fromObject( "{\"Data\": {\"A\": {\"B\": {\"C\": \"c\",\"D\": {}},\"E\": {\"F\": \"f\"},\"G\": {\"H\": \"h\"}},\"A\": {\"B\": {\"C\": \"x\",\"D\": {}},\"E\": {\"F\": \"y\"},\"G\": {\"H\": \"z\"}}}}" );
System.out.println( "net.sf.json.JSONObject: " + jsonObject );
You need to stringify your JSON object
a.toString()
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);
}
}
}
I am using boilerpipe and it seems great, but I want to output JSON. I am using the Java version and testing in NetBeans as follows:
final URL url = new URL("http://mashable.com/2012/09/26/worlds-best-father-kickstarter-calendar");
System.out.println(ArticleExtractor.INSTANCE.getText(url));
Can anyone tell me how I go about this?
Boilerpipe does not come with a JSON serializer.
You can, however, do this (assuming you already extracted all data):
public String articleTextToJson(String article, String title, String sourceUrl) {
if (null == article) {
return "{ \"error\" : { " +
" \"message\" : \"Article did not extract\", " +
" \"code\" : 1 " +
" }, " +
" \"status\" : \"error\" " +
"}";
}
return "{ \"response\" : { " +
" \"title\" : \"" + title + "\" " +
" \"content\" : \"" + article + "\", " +
" \"source\" : \"" + sourceUrl + "\" " +
" }, " +
" \"status\" : \"success\" " +
"}"
}
The tricky part will be of course getting the title...
Or better yet use some JSON serializer like JSONObject.
Hope that helps.