The sum of several items in a json - java

I have a JSON source with more empty_slots elements (in the example exist below only one, but in the reality exist more stations with empty_slots). How can I sum the values from empty_slots and return as double? Thanks!
JAVA
public static double getValueFromJSONString(String jString) throws JSONException
{
JSONObject json = new JSONObject(jString);
return json.getJSONObject("empty_bikes").getDouble(jString);
}
JSON
{"network": {
"company": [
"Gewista Werbegesellschaft m.b.H"
],
"id": "citybike-wien",
"location": {
"city": "Wien",
},
"stations": [
{
"empty_slots": 3,
"extra": {
"slots": "26",
},
"free_bikes": 23
}]}

Checkout JsonPath. Below code is not tested but should work with RestAssured dependency - https://github.com/rest-assured/rest-assured
JsonPath jsonPath = new JsonPath(jsonString);
List<Integer> companyEntityIds = jsonPath.getList("network.stations.empty_slots");
Once you have the array you can just use a stream or whatever to add these up.

Related

Get keys from multiple JSON objects

I have a JSON object that contains undetermined pattern and I need to get all keys of the json object and the sub-objects.
Here's an example of a JSON file:
{
"users": {
"address": [
{
"rue": "ruetest",
"postal": 1111
},
{
"rue": "ruetest",
"postal": 2222
}
],
"type": "string",
"user": [
{
"argent": 122,
"id": 1,
"nom": "user1",
"prenom": "last1"
},
{
"argent": 200,
"id": 2,
"nom": "user2",
"prenom": "last2"
},
{
"argent": 1205,
"id": 3,
"nom": "user3",
"prenom": "last3"
}
]
}
}
and I need to have output like this:
[users,type,address,user,argent,id,nom,prenom] or something like this
I don't think there's really a built-in way to do this, but you could achieve your goal by making a function that does it. Something like (in pseudocode):
public Set getJsonKeys(JSON json) {
Set s = new Set();
for (Entry e : json.entrySet()) {
s.add(e.key);
if (e.value instanceof JSON) s.addAll(getJsonKeys(e.value));
}
return s;
}
I chose a Set rather than List to prevent duplicate entries. If you want to include keys of lists just add a check if e.value is a list and if so, iterate over elements and add getJsonKeys(element) for all elements.
Have you tried the Genson Java Collections mode?
It would give you easy generic access to arbitrary JSON files in java.
If you use the fastjson framework, I think you can use the following code to get all the keys:
JSONObject jsonObject = new JSONObject(jsonData);
Iterator keys = jsonObject.keys();
while (keys.hasNext()){
String key = String.valueOf(keys.next());
}

How would I access this key within a JSON object in Java?

I've been having some problems iterating through a JSON object in Java.
Specifically, I'd like to save each value for "name" to the string array "nameList". I've looked up how to do this, and I haven't found a way for this situation.
String[] nameList = new String[]{};
{
"data": {
"Narray": {
"0":
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
"1":
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
}
}
Ideally you'd want Narray to be an actual JSON array, enclosed in [], with each element being another object, containing the property you need, like this:
{
"Narray": [
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
]
}
Then you can use jackson to decode the JSON string into a POJO structure. Once you have the objects, you can iterate over the array and retrieve the property you need into a list.
I assume that you only want to save each value of name into a String[] (string array), so you don't need to deserialize the JSON string to POJO, just use basic API to achieve what you want as follows:
BTW, your JSON string is invalid, you miss a right bracket.
ObjectMapper mapper = new ObjectMapper();
JsonNode nArray = mapper.readTree(jsonStr).get("data").get("Narray");
String[] nameList = new String[nArray.size()];
for (int i = 0; i < nArray.size(); i++) {
nameList[i] = nArray.get(String.valueOf(i)).get("name").asText();
}
System.out.println(Arrays.toString(nameList));
Console output:
[studio, venue]

Remove a String from Json Object

I am trying to convert an Avro Kafka Event to Json and need to manipulate The Avro Event by Removing Strings from this Event.
I am using GSON Library to manipulate the Json String Object but somehow its not removing the intended String.
JsonElement je = new Gson().fromJson(matchRequest, JsonElement.class);
JsonObject jo = je.getAsJsonObject();
jo.remove("com.XXX.XXXX");
jo.remove("com.XXX.XXX");
jo.remove("com.XXX.XXX");
System.out.println("#################"+jo);
Json String I am Receiving as matchRequest is
{"interaction_id":"321","customer_id":"32","context_id":"123","work_id":"ewq","work_request_id":"213","task_type":"123","match_type":"wert","resource_list":{"com.xxx.xxxx":{"rank":1,"resource_data":{"com.xxx.xxxx":{"account_id":1,"source_name":"Mankind","channel_id":"voice"}}}},"service_list":{"com.xxx.xxxx":{"rank":5,"priority":1,"resource_count":"gvk","min_proficiency":"10","max_proficiency":"1","attributes":{"com.xxx.xxxx":{"category":"edw","value":"33232"}},"resource_offered":{"com.xxx.xxxx":{"agent_id":"rewq","account_id":"123","source_name":"wqe","resource_address":"ewq","source_address":"rewq","channel_id":"212","channel_provider":"wqe"}}}},"matching_state":"OFFERED"}
JSON Format
"interaction_id": "321",
"customer_id": "32",
"context_id": "123",
"work_id": "ewq",
"work_request_id": "213",
"task_type": "123",
"match_type": "wert",
"resource_list": {
"com.XXXXXX": {
"rank": 1,
"resource_data": {
"com.XXXX": {
"account_id": 1,
"source_name": "Mankind",
"channel_id": "voice"
}
}
}
},
"service_list": {
"com.XXXX": {
"rank": 5,
"priority": 1,
"resource_count": "gvk",
"min_proficiency": "10",
"max_proficiency": "1",
"attributes": {
"com.XXXX": {
"category": "edw",
"value": "33232"
}
},
"resource_offered": {
"com.XXXX": {
"agent_id": "rewq",
"account_id": "123",
"source_name": "wqe",
"resource_address": "ewq",
"source_address": "rewq",
"channel_id": "212",
"channel_provider": "wqe"
}
}
}
},
"matching_state": "OFFERED"
}
When you look at the documentation of the remove() method, it needs a key from the JSON object in parameter.
However, the JSON you are receiving does not contain "com.xxx.xxxx" as key, but some keys, like "resource_list", are linked to another JSON object containing "com.xxx.xxxx" as a key.
You may want to look recursively into the JSON object you receive to remove the intended String.
You need to perform your operation over your array:
jo.getAsJsonObject("resource_list").remove("com.XXX.XXXX");
This should do the trick.

Parsing a JSON array WITHOUT a wrapper class

I'm trying to parse a JSON array into a Java ArrayList using Gson.
{
"fathers": [
{
"name": "Donald",
"age": 47,
"children": [
{
"name": "Johnny",
"age": 6
},
{
"name": "Donna",
"age": 15
},
{
"name": "Alan",
"age": 21
}
]
},
{
"name": "George",
"age": 35,
"children": [
{
"name": "Cynthia",
"age": 10
},
{
"name": "Stacey",
"age": 5
},
{
"name": "Dewey",
"age": 2
}
]
}
]
}
I'm trying to parse the "fathers" array into an ArrayList... However, I can't do it directly, since the fathers array is wrapped by a JSON object. Normally, I would do something like this:
Type fathersListType = new TypeToken<ArrayList<Father>>(){}.getType();
fathersArrayList = gson.fromJson(fathersJson, fathersListType);
But, since the fathers array is wrapped by an object, I get this error:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Is there a way to parse said array, without having to declare a wrapper class, that contains a "fathers" array? Like ignoring the wrapping object, or extracting the JSON array from it.
You can parse the root object as a Map:
Type rootType = new TypeToken<Map<String, List<Person>>>(){}.getType();
Map<String, List<Person>> root = gson.fromJson(fathersJson, rootType);
List<Person> fathersList = root.get("fathers");
Something like this should work:
String data = "{...}"; // Your JSON
JsonArray array = new JsonParser().parse(data).getAsJsonObject().get("fathers").getAsJsonArray();
List<Father> fathers = Arrays.asList(new Gson().fromJson(array, Father[].class));
Arrays.asList comes from https://commons.apache.org/

Iterate last values present in a JSON response using java

I need to iterate and get the last values like name, url and color from below JSON response. Using java/gson api. Please help me on this.
{
"Title": {
"desc": [
{
"name": "PRE_DB",
"url": "http://jenkins.example.com/job/my_first_job/",
"color": "blue_anime"
},
{
"name": "SDD_Seller_Dashboard",
"url": "http://jenkins.example.com/job/my_second_job/",
"color": "blue_anime"
}
]
}
}
example output :
name : SDD_Seller_Dashboard
color :blue_anime
JSONObject data = new JSONObject(your_JSON_Repsonse);
JSONArray data_desc=data.getJSONArray(desc);
for(int i=0;i<=data_desc.length();i++)
{
name=data_desc.getString("name");
url=data_desc.getString("url");
color=data_desc.getString("color");
}

Categories

Resources