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
}
}
Related
I want to extract the COUNT OF session which are of null values from the below json. I tried with online json path extractor its work but the tried on java code with JsonPath lib, its showing parameter is not defind.
*{
"value": {
"ready": true,
"message": "Selenium Grid ready.",
"nodes": [
{
"id": "eaef55e8-18a3-490f-a6a5-0a1cce762e80",
"uri": "xyz",
"maxSessions": 4,
"osInfo": {
"arch": "amd64",
"name": "Windows 10",
"version": "10.0"
},
"heartbeatPeriod": 60000,
"availability": "UP",
"version": "4.3.0 (revision a4995e2c09*)",
"slots": [
{
"id": {
"hostId": "eaef55e8-18a3-49f-a6a5-0acce762e80",
"id": "9e4bce35-f596-476f-ab0f-b5df17e02099"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
},
{
"id": {
"hostId": "eaef55e8-18a3-490f-a6a5-0a5cce762e80",
"id": "bab6efd1-ed0d-450a-85db-13cbd6c8f6e6"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
},
{
"id": {
"hostId": "eaef55e8-18a3-490f-a6a5-0acce762e80",
"id": "5307491a-3ce7-4dc2-98b7-2e8dd1a9dbc2"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
},
{
"id": {
"hostId": "eaef55e8-18a3-490f-a6a5-05cce762e80",
"id": "0856bb3b-3a47-44bf-a532-4b4f0298ef95"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
}
]
},
{
"id": "8311f460-496b-4181-9960-19bd5cfaa125",
"uri": "http:\u002f\u002f172.18.32.1:5555",
"maxSessions": 4,
"osInfo": {
"arch": "amd64",
"name": "Windows 10",
"version": "10.0"
},
"heartbeatPeriod": 60000,
"availability": "UP",
"version": "4.3.0 (revision a4995e2c09*)",
"slots": [
{
"id": {
"hostId": "8311f460-496b-4181-9960-19bdcfaa125",
"id": "39b50d92-9cb8-47a1-985b-b3e965453a0d"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
},
{
"id": {
"hostId": "8311f460-496b-4181-990-19bdfaa125",
"id": "76e691c7-fab5-493a-bc2f-317a2776e5cf"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
},
{
"id": {
"hostId": "8311f460-496b-4181-9960-19bd5cfaa125",
"id": "0692a825-2b83-462e-9a5c-dfcae77c033a"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
},
{
"id": {
"hostId": "8311f460-496b-4181-9960-19bd5cfaa125",
"id": "10aa0cd9-e9a5-4070-87b6-52a4201e9bc0"
},
"lastStarted": "1970-01-01T00:00:00Z",
"session": null,
"stereotype": {
"browserName": "chrome",
"platformName": "Windows 10"
}
}
]
}
]
}
}*
Could you please help me to get the exact path which will work on java too with the given condition.
Thank you in advance.
If you are using Restassured's JsonPath, i.e. "io.restassured.path.json.JsonPath", please remember that it uses a Gpath expression and hence the expression for JayWay's JsonPath would not work here.
For your json payload, the below code should work using RestAssured:
import java.util.List;
import java.util.Map;
import io.restassured.path.json.JsonPath;
...
public static int countOfSessions(String json) {
JsonPath js = new JsonPath(json);
List<Map> ls = js.param("sessVal", null).get("value.nodes.flatten().slots.flatten().findAll {s -> s.session == sessVal}.session");
return ls.size();
}
You may consider another library Josson for the solution.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
"{" +
" \"value\": {" +
" \"ready\": true," +
" \"message\": \"Selenium Grid ready.\"," +
" \"nodes\": [" +
" {" +
" \"id\": \"eaef55e8-18a3-490f-a6a5-0a1cce762e80\"," +
" \"uri\": \"xyz\"," +
" \"maxSessions\": 4," +
" \"osInfo\": {" +
" \"arch\": \"amd64\"," +
" \"name\": \"Windows 10\"," +
" \"version\": \"10.0\"" +
" }," +
" \"heartbeatPeriod\": 60000," +
" \"availability\": \"UP\"," +
" \"version\": \"4.3.0 (revision a4995e2c09*)\"," +
" \"slots\": [" +
" {" +
" \"id\": {" +
" \"hostId\": \"eaef55e8-18a3-49f-a6a5-0acce762e80\"," +
" \"id\": \"9e4bce35-f596-476f-ab0f-b5df17e02099\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }," +
" {" +
" \"id\": {" +
" \"hostId\": \"eaef55e8-18a3-490f-a6a5-0a5cce762e80\"," +
" \"id\": \"bab6efd1-ed0d-450a-85db-13cbd6c8f6e6\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }," +
" {" +
" \"id\": {" +
" \"hostId\": \"eaef55e8-18a3-490f-a6a5-0acce762e80\"," +
" \"id\": \"5307491a-3ce7-4dc2-98b7-2e8dd1a9dbc2\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }," +
" {" +
" \"id\": {" +
" \"hostId\": \"eaef55e8-18a3-490f-a6a5-05cce762e80\"," +
" \"id\": \"0856bb3b-3a47-44bf-a532-4b4f0298ef95\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }" +
" ]" +
" }," +
" {" +
" \"id\": \"8311f460-496b-4181-9960-19bd5cfaa125\"," +
" \"uri\": \"http:\\u002f\\u002f172.18.32.1:5555\"," +
" \"maxSessions\": 4," +
" \"osInfo\": {" +
" \"arch\": \"amd64\"," +
" \"name\": \"Windows 10\"," +
" \"version\": \"10.0\"" +
" }," +
" \"heartbeatPeriod\": 60000," +
" \"availability\": \"UP\"," +
" \"version\": \"4.3.0 (revision a4995e2c09*)\"," +
" \"slots\": [" +
" {" +
" \"id\": {" +
" \"hostId\": \"8311f460-496b-4181-9960-19bdcfaa125\"," +
" \"id\": \"39b50d92-9cb8-47a1-985b-b3e965453a0d\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }," +
" {" +
" \"id\": {" +
" \"hostId\": \"8311f460-496b-4181-990-19bdfaa125\"," +
" \"id\": \"76e691c7-fab5-493a-bc2f-317a2776e5cf\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }," +
" {" +
" \"id\": {" +
" \"hostId\": \"8311f460-496b-4181-9960-19bd5cfaa125\"," +
" \"id\": \"0692a825-2b83-462e-9a5c-dfcae77c033a\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }," +
" {" +
" \"id\": {" +
" \"hostId\": \"8311f460-496b-4181-9960-19bd5cfaa125\"," +
" \"id\": \"10aa0cd9-e9a5-4070-87b6-52a4201e9bc0\"" +
" }," +
" \"lastStarted\": \"1970-01-01T00:00:00Z\"," +
" \"session\": null," +
" \"stereotype\": {" +
" \"browserName\": \"chrome\"," +
" \"platformName\": \"Windows 10\"" +
" }" +
" }" +
" ]" +
" }" +
" ]" +
" }" +
"}");
Query
// Get all the slots with session=null
JsonNode node = josson.getNode(
"value.nodes.slots[session=null & stereotype.platformName='Windows 10']*");
System.out.println(node.toPrettyString());
// Get the COUNT
node = josson.getNode(
"value.nodes.slots[session=null & stereotype.platformName='Windows 10']*.size()");
System.out.println(node.toPrettyString());
// Use wildcard search
node = josson.getNode(
"*().slots[session=null & stereotype.platformName='Windows 10']*.size()");
System.out.println(node.toPrettyString());
I am usng google DirectionsResul Object
And then I want to using Object mapper to mapping this json to DirectionsResul Object
{
"geocoded_waypoints": [],
"routes": [
{
"bounds": {},
"legs": [
{
"distance": {
"human_readable": "13 km",
"in_meters": 13175
},
"duration": {
"human_readable": "37 phút",
"in_seconds": 2206
},
"steps": []
}
],
"overview_polyline": {
"points": "aaaa"
},
"warnings": [],
"waypoint_order": []
}
]
}
Using this code
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
DirectionsResult result;
result = objectMapper.readValue(json, DirectionsResult.class.);
All is ok but overview_polyline can't mapping, the points value is null
and I see in the EncodedPolyline have a contractor like this
public EncodedPolyline() {
this.points = null;
}
So how can I mapping the points value to the DirectionsResul Object
Here is my result I got
Here is all the code that can run
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.maps.model.DirectionsResult;
public void testGetDirections() throws NetworkException {
String json = "{\n" +
" \"geocoded_waypoints\": [],\n" +
" \"routes\": [\n" +
" {\n" +
" \"bounds\": {\n" +
" \"northeast\": {\n" +
" \"lat\": 34.1358593,\n" +
" \"lng\": -117.922066\n" +
" },\n" +
" \"southwest\": {\n" +
" \"lat\": 33.815582,\n" +
" \"lng\": -118.3516983\n" +
" }\n" +
" },\n" +
" \"legs\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"13 km\",\n" +
" \"in_meters\": 13175\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"37 phút\",\n" +
" \"in_seconds\": 2206\n" +
" },\n" +
" \"steps\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"10 ft\",\n" +
" \"in_meters\": 3\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"1 min\",\n" +
" \"in_seconds\": 0\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"overview_polyline\": {\n" +
" \"points\": \"{ashdasda}\"\n" +
" },\n" +
" \"warnings\": [],\n" +
" \"waypoint_order\": []\n" +
" }\n" +
" ]\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
DirectionsResult goongMapsDirectionResult;
try {
goongMapsDirectionResult = objectMapper.readValue(json, DirectionsResult.class.);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
The problem is that there is no setter for points on EncodedPolyline.
One way to work around this is to use a DeserializationProblemHandler:
public class SO69242058 {
public static void main(String args[]) throws JsonProcessingException {
String json = "{\n" +
" \"geocoded_waypoints\": [],\n" +
" \"routes\": [\n" +
" {\n" +
" \"bounds\": {\n" +
" \"northeast\": {\n" +
" \"lat\": 34.1358593,\n" +
" \"lng\": -117.922066\n" +
" },\n" +
" \"southwest\": {\n" +
" \"lat\": 33.815582,\n" +
" \"lng\": -118.3516983\n" +
" }\n" +
" },\n" +
" \"legs\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"13 km\",\n" +
" \"in_meters\": 13175\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"37 phút\",\n" +
" \"in_seconds\": 2206\n" +
" },\n" +
" \"steps\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"10 ft\",\n" +
" \"in_meters\": 3\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"1 min\",\n" +
" \"in_seconds\": 0\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"overview_polyline\": {\n" +
" \"points\": \"{ashdasda}\"\n" +
" },\n" +
" \"warnings\": [],\n" +
" \"waypoint_order\": []\n" +
" }\n" +
" ]\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
//objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.addHandler(new DeserializationProblemHandler() {
#Override
public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p,
JsonDeserializer<?> deserializer, Object beanOrClass,
String propertyName) throws IOException {
EncodedPolyline encodedPolyline = (EncodedPolyline)beanOrClass;
try {
Field f = EncodedPolyline.class.getDeclaredField("points");
f.setAccessible(true);
f.set(encodedPolyline, p.readValueAs(String.class));
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
return true;
}
});
DirectionsResult goongMapsDirectionResult;
goongMapsDirectionResult = objectMapper.readValue(json, DirectionsResult.class);
}
}
I've removed objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) so that the error occurs when Jackson tries to set points. Then we set it reflectively.
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);
}
}
}