How to convert the tree structured json to Java object using gson - java

[
{
"sentence": "I want to buy shoes .",
"tree": {
"ROOT": [
{
"index": 2,
"token": "want",
"label": "VERB",
"pos": "VBP",
"tree": {
"nsubj": [
{
"index": 1,
"token": "I",
"label": "PRON",
"pos": "PRP"
}
],
"xcomp": [
{
"index": 4,
"token": "buy",
"label": "VERB",
"pos": "VB",
"tree": {
"aux": [
{
"index": 3,
"token": "to",
"label": "PRT",
"pos": "TO"
}
],
"dobj": [
{
"index": 5,
"token": "shoes",
"label": "NOUN",
"pos": "NNS"
}
]
}
}
],
"punct": [
{
"index": 6,
"token": ".",
"label": ".",
"pos": "."
}
]
}
}
]
}
}
]
This is tree represented in Json. But the keys for nested nodes keep changing.
For example "ROOT, nsubj, xcomp" ... etc.
How do I convert above json code to Java Object using gson.
Above response is from syntaxnet Parsey_Mcparseface api I'm trying to use.
Thanks in advance.

Gson has a method Gson#fromJson. For example, this is a code to read a simple String object.
Gson gson = new Gson();
String str = gson.fromJson("\"hello\"", String.class);
System.out.println("String: " + str);
You need to prepare Java Object to read your proposed JSON. But, you don't need to write code by yourself. There is a website providing automatical JSON object generator.
jsonschema2pojo
enter following items:
Target language: Java
Source type: JSON
Annotation type: Gson
and enter your class name, for example "ParsedSentence"
then, write code. You will get object.
Gson gson = new Gson();
ParsedSentence parsed = gson.fromJson(longLongJsonString, ParsedSentence.class);

Related

How to remove an attribute from RequestSpecification/FilterableRequestSpecification body?

Dears,
I am working on creating a simple method which will take String argument which will be a path or other kind "pointer" to attribute/s in JSON and this method will remove those attribute/s.
My problem is I can find values of those attribute/s using JsonPath, but I can't find methods in rest assured (or other libraries) which could remove/delete attributes by given path.
JSON is already added earlier so i need to pull him from RequestSpecification or FilterableRequestSpecification object ex.
RequestSpecification rs = *objFromContext*;
FilterableRequestSpecification frs= (FilterableRequestSpecification) rs;
frs.getBody();
I've tried to work with JSONObject class and remove() but it doesn't work on complex JSONs.
given example JSON
{
"created": "string",
"updated": "string",
"items": [
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value1",
"name": "name",
"value": 123
}
]
},
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value2",
"name": "name",
"value": 123
}
]
}
],
"timer": {
"startDate": "2015-01-01",
"endDate": "2021-01-02"
},
"id": "myId"
}
using JsonPath jp = JsonPath.from(httpRequest.getBody().toString());
and then jp.get(items.itemsproperties.code) i can find value1 and value2.
I stuck in this point: How to remove those attributes from sended body?
I know i can convert body into JSONObject and then go field after field conversion between getJSONArray and GetJSONOBject and remove those fields, but i would like to make this metod much more universal.
Is this possible?
If you want to manipulate json in Rest-Assured JsonPath, then the answer is No. You can't do that. JsonPath help you to extract value from json, that's it, no more.
You have to use different libraries to remove key-value pair.
For example: using JsonPath Jayway
DocumentContext parse = JsonPath.parse(body);
parse.delete("$..itemsProperties..code");
System.out.println(parse.jsonString());

Filter nested json data using jsonpath as in example

I am using jsonpath to filter.
Json(Dummy json just to explain) source String, which is basically a list of Operating systems and details of its programs etc. In this example, the OS whose id = 1403 is a windows 10 OS and has 2 features acchritecture and browser. There are more details to the browser feature as shown in json
[
{
"id": 1403,
"os": "window 10",
"features": [
{
"id": 1356,
"name": "architecture",
"value": [
{
"id": 1308,
"feature": [
{
"id": 1262,
"key": "name",
"value": "amd64"
}
]
}
],
"category": "cat1"
},
{
"id": 1357,
"name": "browser",
"value": [
{
"id": 1309,
"feature": [
{
"id": 1263,
"key": "name",
"value": "Firefox"
},
{
"id": 1265,
"key": "version",
"value": "187"
}
]
}
],
"category": "cat2"
}
]
},
{
"id": 2804,
"os": "window 7",
"features": [
{
"id": 2764,
"name": "architecture",
"value": [
{
"id": 2719,
"feature": [
{
"id": 2679,
"key": "name",
"value": "amd64"
}
]
}
],
"category": "cat1"
},
{
"id": 2765,
"name": "browser",
"value": [
{
"id": 2722,
"feature": [
{
"id": 2685,
"key": "name",
"value": "Chrome"
},
{
"id": 2684,
"key": "version",
"value": "87.0.4280.88"
}
]
}
],
"category": "cat2"
}
]
}
]
I want to be able to filter the json such that
features[*].name == 'browser' and features[*].value[*].feature[*].value == 'chrome'
What will be the JsonPath string that can help me achieve above query? The above query uses similar syntax used by JsonPath string but doesn't do the job. Its just to explain.
There is another example here gets Movie Title Given 'Starring' field
And would like to get the full OS json that fulfils this condition. In this case a array of OS which contains only one OS i.e. with id= 2804
[
{
"id": "2804",
...
}
]
I am stuck much before what aim to achieve. Here is my code to get all the OS that have "name=browser". I get the array but it only contains value[] items. I want it get the full json. It returns object with IDs- 1357, 2765.
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
.read("$[*].features[*].[?(#.name == 'browser')]");
To get the outer array you need to use the filter like $[?(...)]
For your current use case, we need to use nested array filters. There is an open issue in JsonPath for filter on children level. (Refer here).
Luckily, there is a workaround suggested to use contains over here.
we can use the below expression to filter:
List<Object> expensive = JsonPath.parse(jsonDataSourceString)
.read("$[?(#.features[?(#.name == 'browser')].value[*].feature[*].value contains 'Chrome')]");
Prints the below output
{id=2804, os=window 7, features=[{"id":2764,"name":"architecture","value":[{"id":2719,"feature":[{"id":2679,"key":"name","value":"amd64"}]}],"category":"cat1"},{"id":2765,"name":"browser","value":[{"id":2722,"feature":[{"id":2685,"key":"name","value":"Chrome"},{"id":2684,"key":"version","value":"87.0.4280.88"}]}],"category":"cat2"}]}

Jayway JsonPath query to get required json format

I need to extract a json in required format from input json. i'm using jayway json path library. How to achieve it ?
Input Json:
{
"ccid": [
{
"id": 13,
"src": {
"sname": "XA-SXXD",
"lname": "John",
"identifier": 2,
"StatusCode": "C"
}
},
{
"id": 14,
"src": {
"sname": "XB-SXXD",
"lname": "Cena",
"identifier": 3,
"StatusCode": "C",
}
}
]
}
Required Format:
[ {
"id": "13",
"sources": {
"sname": "XA-SXXD",
"lname": "John",
"identifier": 2
}
},
{
"id": "14",
"sources": {
"sname": "XB-SXXD",
"lname": "Cena",
"identifier": 3
}
}]
Query that i use:
$.ccid[*].src[?(#.identifier!=null)].['identifier','sname']
Output that i get:
[
{
"identifier" : 2,
"sname" : "XA-SXXD"
},
{
"identifier" : 3,
"sname" : "XB-SXXD"
}
]
Kindly help me to modify my query to get the required format. The string "sources" in the required format can be hardcoded.
I think I managed to solve this :)
$.ccid[*].[?(#.src.identifier!=null)].['id', 'src']
Give it a try.
Input tested on:
{
"ccid": [
{
"id": 13,
"src": {
"sname": "XA-SXXD",
"lname": "John",
"StatusCode": "C"
}
},
{
"id": 14,
"src": {
"sname": "XB-SXXD",
"lname": "Cena",
"identifier": null,
"StatusCode": "C",
}
}
]
}
Output received:
[
{
"id" : 13,
"src" : {
"sname" : "XA-SXXD",
"lname" : "John",
"StatusCode" : "C"
}
}
]
Only problem is saw is if identifier tag is not available it's essentially treated as not-null. Hence we are getting 13 as an output. But if value is explicitly null then it's fine. So the needs to be enhanced a bit more.
Hope this helps.

how to create linked hash map object for this json

I am trying to call an API using Retrofit in android. For this API I need the input parameter JSON object in proper sequence.
Only if I have the json in required sequence I get successful response from the API, otherwise it gives an error. To handle this issue I got one solution that is to first create a LinkedHashMap of input parameter then create the JSON of that LinkedHashMap. This way I'm acheaving the response from api.
but right now im confused how to create linkedHash map for below json
{
"RequestXml": {
"Authenticate": {
"InterfaceCode": "1",
"InterfaceAuthKey": "AirticketOnlineWebSite",
"AgentCode": "MOS0000001",
"Password": "KGBW5P"
},
"BookTicketRequest": {
"TrackNo": "0$182967|4|1AO",
"MobileNo": "9099776464",
"AltMobileNo": "9898989898",
"Email": "abc#gmail.com",
"Address": "Test",
"ClientRequestID": "",
"Passengers": {
"Passenger": [
{
"PaxSeqNo": "1",
"Title": "Mr",
"FirstName": "Savan",
"LastName": "Test",
"PassengerType": "A",
"DateOfBirth": "01/12/1992",
"PassportNo": "RTTTTGGBGB56356",
"PassportExpDate": "01/12/2024",
"PassportIssuingCountry": "IND",
"NationalityCountry": "IND"
}
]
},
"Segments": {
"Segment": [
{
"TrackNo":"0$182967|4|1AO",
"SegmentSeqNo": "1",
"AirlineCode": "UK",
"FlightNo": "888",
"FromAirportCode": "BOM",
"ToAirportCode": "DEL",
"DepDate": "30/09/2019",
"DepTime": "14:00",
"ArrDate": "30/09/2019",
"ArrTime": "16:00",
"FlightClass": "E",
"MainClass": "Y"
}
]
},
"AdditionalServices": {
},
"TotalAmount": "4735",
"MerchantCode": "PAY9zJhspxq7m",
"MerchantKey": "eSpbcYMkPoZYFPcE8FnZ",
"SaltKey": "WHJIIcNjVXaZj03TnDme",
"IsTicketing": "Yes"
}
}
}

Parsing JSON with Java from a dictionary api

Very new to JSON. Using json-lib for this and been pulling my hair out trying to get "definitions" from this JSON response by Oxford Dictionaries API. Tried all sorts of things. But can never get anything more specific than everything from "results". Would like to figure out why this is so difficult otherwise will just resort to regex.
JSONObject obj = new JSONObject(stringBuilder.toString());
JSONArray arr = obj.getJSONArray("results");
String test = arr.getJSONObject(1).toString(); // Empty wtf?
String definition = obj.getString("definitions"); // empty also...
Managed to also access "id", "language" and "lexicalEntries" separately, but anything beyond that doesn't seem to want to cooperate.... Is this a normal JSON response? It's quite awkward no? Thanks...
JSON:
{
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "ace",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"homographNumber": "000",
"senses": [
{
"definitions": [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
],
"id": "m_en_gbus0005680.006"
},
{
"definitions": [
"a person who excels at a particular sport or other activity"
],
"id": "m_en_gbus0005680.010",
"subsenses": [
{
"definitions": [
"a pilot who has shot down many enemy aircraft"
],
"id": "m_en_gbus0005680.011"
}
]
},
{
"definitions": [
"(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
],
"id": "m_en_gbus0005680.013",
"subsenses": [
{
"definitions": [
"a hole in one"
],
"id": "m_en_gbus0005680.014"
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Noun",
"text": "ace"
},
{
"entries": [
{
"homographNumber": "001",
"senses": [
{
"definitions": [
"very good"
],
"id": "m_en_gbus0005680.016"
}
]
}
],
"language": "en",
"lexicalCategory": "Adjective",
"text": "ace"
},
{
"entries": [
{
"homographNumber": "002",
"senses": [
{
"definitions": [
"(in tennis and similar games) serve an ace against (an opponent)"
],
"id": "m_en_gbus0005680.020",
"subsenses": [
{
"definitions": [
"score an ace on (a hole) or with (a shot)"
],
"id": "m_en_gbus0005680.026"
}
]
},
{
"definitions": [
"achieve high marks in (a test or exam)"
],
"id": "m_en_gbus0005680.028",
"subsenses": [
{
"definitions": [
"outdo someone in a competitive situation"
],
"id": "m_en_gbus0005680.029"
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Verb",
"text": "ace"
}
],
"type": "headword",
"word": "ace"
}
]
}
String jsonData = sb.toString();
JSONObject obj = new JSONObject(jsonData);
JSONArray resultsArr = obj.getJSONArray("results");
String test = resultsArr.getJSONObject(0).toString();
JSONArray lexicalEntriesArr = resultsArr.getJSONObject(0).getJSONArray("lexicalEntries");
JSONArray entriesArr = lexicalEntriesArr.getJSONObject(0).getJSONArray("entries");
JSONArray sensesArr = entriesArr.getJSONObject(0).getJSONArray("senses");
JSONArray definitionsArr = sensesArr.getJSONObject(0).getJSONArray("definitions");
String definition = definitionsArr.toString();
Reference: http://jsonviewer.stack.hu/
Watch carefully the way we traverse the JSON object and when we should use getJSONObject & getJSONArray methods to retrieve the particular type of data we want from JSON Object.
Update: You might want to iterate the JSON array as per your requirement. I have just explained the case as in how to reach till definitions.

Categories

Resources