Java extract information from JSON - java

I have the following JSON object:
{
"_class": "hudson.model.FreeStyleBuild",
"actions": [
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
}
]
},
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
}
]
},
{
},
{
"_class": "com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction"
},
{
},
{
},
{
}
],
"artifacts": [
],
"building": false,
"description": null,
"displayName": "#2",
"duration": 15,
"estimatedDuration": 61,
"executor": null,
"fullDisplayName": "gcimpoies-test5 #2",
"id": "2",
"keepLog": false,
"number": 2,
"queueId": 6,
"result": "FAILURE",
"timestamp": 1522153325922,
"url": "http://localhost:8080/job/gcimpoies-test5/2/",
"builtOn": "",
"changeSet": {
"_class": "hudson.scm.EmptyChangeLogSet",
"items": [
],
"kind": null
},
"culprits": [
]
}
And I want to extract the username: SYSTEM
I tried using JsonSlurper but with no luck. I believe the right way to go is using JSONObject instead.
Any help is much appreciated.

You can use Google Gson for parsing json in java. Here I am pasting the code to convert json into Map. So that you can simply access json as map object.
Map map = gson.fromJson(jsonString, Map.class);
System.out.println(map);
For more info, please read this thread.

Gson gson = new Gson();
Map buildDetailsMap;
buildDetailsMap = gson.fromJson(json, Map.class);
if (buildDetailsMap != null) {
List actions = (List) buildDetailsMap.get("actions");
Map actionZero = (Map) actions.get(0);
List causes = (List) actionZero.get("causes");
Map causeZero = (Map) causes.get(0);
username = (String) causeZero.get("userName");
}
This is how I did it. Thanks SV Madhava Revy

Related

MongoDB Autocomplete index doesn't get result

I have a collection which name called 'airport' and i have Atlas Auto Complete index you can see JSON config below.
{
"mappings": {
"dynamic": false,
"fields": {
"name": [
{
"type": "string"
},
{
"foldDiacritics": false,
"maxGrams": 7,
"minGrams": 2,
"type": "autocomplete"
}
]
}
}
}
and this is my Document record
{
"_id": {
"$oid": "63de588c7154cc3ee5cbabb2"
},
"name": "Antalya Airport",
"code": "AYT",
"country": "TR",
"createdDate": {
"$date": {
"$numberLong": "1675516044323"
}
},
"updatedDate": {
"$date": {
"$numberLong": "1675516044323"
}
},
"updatedBy": "VISITOR",
"createdBy": "VISITOR",
}
And This is my MongoDB Query
public List<Document> autoCompleteAirports(AutoCompleteRequest autoCompleteRequest) {
return database.getCollection(AIRPORT).aggregate(
Arrays.asList(new Document("$search",
new Document("index", "airportAutoCompleteIndex")
.append("text",
new Document("query", autoCompleteRequest.getKeyword())
.append("path", "name")
)))
).into(new ArrayList<>());
}
So, when i type "antalya" or "Antalya", this works. But when i type "Antaly" or "antal" there is no result.
Any solution ?
i tried change min and max grams settings on index

Is there an easy way to flatten a json:api response on Android?

I'm trying to flatten the below response without having to parse it into a class. The reason for this is that the server could add or remove fields at anytime so it needs to be dynamic. We also have another service that returns lookup paths that we use to get data out of the flattened response - like "$.detail.att_one" There is a library for iOS that does the exact thing I'm looking for but as far as I can find nothing similar for Android: https://github.com/infinum/Japx
{
"data": [
{
"type": "items",
"id": "14",
"attributes": {
"item_type": "shape_circle",
"code": null,
"size": "70"
},
"relationships": {
"detail": {
"data": {
"type": "circle",
"id": "90"
}
},
"metadata": {
"data": "metadata"
}
},
"links": {
"self": "http://url/item/14"
}
}
],
"included": [
{
"type": "circle",
"id": "90",
"attributes": {
"att_one": 4,
"att_two": "11111111111",
"att_three": "Bob"
}
}
]}
The result I'm looking for:
{
"data": [
{
"id": "14",
"type": "items",
"item_type": "shape_circle",
"code": null,
"size": "70",
"metadata": {
"data": "metadata"
},
"detail": {
"type": "circle",
"id": "90",
"att_one": 4,
"att_two": "11111111111",
"att_three": "Bob"
},
"links": {
"self": "http://url/item/14"
}
}
]}
There is a nice JSONAPI library that does the thing, but you have to define resource classes for it.
Check out jasminb/jsonapi-converter
It recursively flattens all the included relationships and handles inheritance.

How can I perform a sub-filter using JsonPath?

I've read the documentation, and I can't figure out how I perform a sub-filter using JsonPath. Here's an example...
Given the following JSON, how do I retrieve a list of people with an address in Sydney?
I've tried variations of $.people[?(#.addresses[*].city=="Sydney")] to no avail. e.g.
$.people[?(#.addresses[*].city=="Sydney")]
$.people[?(#.addresses.city=="Sydney")]
$.people[?(#..city=="Sydney")]
JSON
{
"people": [{
"name": "George",
"addresses": [{
"city": "Sydney"
}]
},
{
"name": "Jane",
"addresses": [{
"city": "Brisbane"
}]
},
{
"name": "Fred",
"addresses": [{
"city": "Perth"
},
{
"city": "Sydney"
}
]
}
]
}
Preferred Output
{
"people": [{
"name": "George",
"addresses": [{
"city": "Sydney"
}]
},
{
"name": "Fred",
"addresses": [{
"city": "Perth"
},
{
"city": "Sydney"
}
]
}
]
}
I'm using the following Java library: com.jayway.jsonpath:json-path:2.2.0
I'm using http://jsonpath.com/ to test my jsonpath in the browser (maybe that's the problem?).
The problem is that #.addresses[*].city is a collection. It is not ANY city of the person and it is not ONLY(each) city of the person.
If you are looking for persons with some addresses in Sydney the query should be:
"$.people[?(\"Sydney\" in #.addresses[*].city)]"
Example:
String filter = "$.people[?(\"Sydney\" in #.addresses[*].city)]";
ReadContext ctx = JsonPath.parse(json);
List<Map<String, Object>> rez = ctx.read(filter, List.class);
If you are looking for persons with all addresses in Sydney I do not know correct query. It is possible to use Predicate, but it is very complicated code.
Just for information:
List<Map<String, Object>> rez = JsonPath.parse(json).read(
"$.people[?]",
List.class,
new Predicate() {
#Override
public boolean apply(PredicateContext ctx) {
Map<String, Object> map = ctx.item(Map.class);
ReadContext readContext = JsonPath.parse(JSONObject.toJSONString(map));
List<String> allAddresses = readContext.read("$.addresses[*].city");
List<String> sydneyAddresses = readContext.read("$.addresses[?(#.city=='Sydney')].city");
return allAddresses.size() == sydneyAddresses.size();
}
});
First create a filter
String jsonData = "{
"people": [{
"name": "George",
"addresses": [{
"city": "Sydney"
}]
},
{
"name": "Jane",
"addresses": [{
"city": "Brisbane"
}]
},
{
"name": "Fred",
"addresses": [{
"city": "Perth"
},
{
"city": "Sydney"
}
]
}
]
}"
Filter expensiveFilter = Filter.filter(Criteria.where(['people'][*]['address']['city'].eq("Sydney"));
Now you can add this in your JsonPath
String peoples = JsonPath.parse(jsonData).read("$['people'][?]", expensiveFilter).toString();

Building JSON programmatically in java

I need to build a below JSON programmatically. But,need a elegant way to convert from Java object to JSON. so that, i can avoid string builder to build the below JSON.
I aware of that, sometimes,I have array of parameters for the specific key while building JSON.
Please share the generic way to solve that.
Please share some thoughts to this.
{
"tropo": [
{
"ask": {
"attempts": 3,
"say": [
{
"value": "Hi.",
"event": "timeout"
},
{
"value": "Hello",
"event": "nomatch:1"
},
{
"value": "Hello2",
"event": "nomatch:2"
},
{
"value": "Satheesh",
"voice": "veronica"
}
],
"choices": {
"value": "Yes(1,Yes),No(2,No)",
"mode": "ANY"
},
"voice": "veronica",
"recognizer": "en-us",
"timeout": 8,
"name": "year",
"minConfidence": 39,
"required": true
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "continue"
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "incomplete"
}
},
{
"on": {
"next": "",
"event": "hangup"
}
}
]
}
As paulsm4 said, I'd have a look at gson. It's easy to use, you can find a lot of example of how it works all over the web (official user guide).
Example:
Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));
Gson gson = new Gson();
System.out.println(gson.toJson(employee));
Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}
From howtodoinjava.com/'s Google Gson Tutorial : Convert Java Object to / from JSON.

Issue with json Content type for DeepInsert

I'm trying deepinsert with Json on the service,http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/OData/OData.svc/Categories with body--
{
"d" : {
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Categories(0)", "type": "ODataDemo.Category"
}, "ID": 97, "Name": "Food", "Products": [
{
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products( 0)", "type": "ODataDemo.Product"
}, "ID": 97, "Name": "Bread", "Description": "Whole grain bread", "ReleaseDate": "\/Date(694224000000)\/", "DiscontinuedDate": null, "Rating": 4, "Price": "2.5", "Category": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Category"
}
}, "Supplier": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Supplier"
}
}
}
]
}
}
and I get the 400 Bad request with error description:
{
error: {
code: ""
message: {
lang: "en-US"
value: "Error processing request stream. The property name 'd' specified for type 'ODataDemo.Category' is not valid."
}-
}-
}
Can someone help me figure out what I'm doing wrong here?
There is no need to append "d" in the body of post request.
Remove the "d" and send the body like this:
{
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Categories(0)", "type": "ODataDemo.Category"
}, "ID": 97, "Name": "Food", "Products": [
{
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products( 0)", "type": "ODataDemo.Product"
}, "ID": 97, "Name": "Bread", "Description": "Whole grain bread", "ReleaseDate": "\/Date(694224000000)\/", "DiscontinuedDate": null, "Rating": 4, "Price": "2.5", "Category": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Category"
}
}, "Supplier": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Supplier"
}
}
}
]
}

Categories

Resources