Suppose I have a json as
{
"data": {
"json": [
{
"value": [
"john","joy"
],
"key": "Names"
},
{
"value": [
"25A",
"26B"
],
"key": "john"
},
{
"value": [
"27A",
"28B"
],
"key": "joy"
}
]
}
}
I want to do create a Dynamic ArrayList names for each values as shown below
for(String name:Names){
//create a dynamic arraylist from the names here like
// ArrayList<String> joy= ..........
}
Can Anyone help me with this please?
Maybe use
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("arrayname", new ArrayList<String>());
Related
Now i take JsonObject from API like this:
Its XML object converted to JsonObject.
"Details": {
"row": [
{
"item": [
{
"name": "Account",
"value": 12521512
},
{
"name": "ACCNO",
"value": 4214
},
{
"name": "Number",
"value": 5436
}
]
},
"item": [
{
"name": "Account",
"value": 5789678
},
{
"name": "ACCNO",
"value": 6654
},
{
"name": "Number",
"value": 0675
}
]
},
But i need convert this object and send like this:
{
"Details": {
"row": [
{
"Account": 12521512,
"ACCNO": 4214,
"Number": 12412421
},
{
"Account": 5789678,
"ACCNO": 6654,
"Number": "0675"
}
]
}
}
I have rows more than 1000, i need faster way to handle.
How to handle, please help me
You could use the JSON-java library to parse your input and transform it to your desired format. Something like this works but you may need to adjust it to your needs:
JSONObject jsonObject = new JSONObject(json); // Load your json here
JSONObject result = new JSONObject("{\"Details\": {\"row\": []}}");
for (Object row : jsonObject.getJSONObject("Details").getJSONArray("row")) {
if (!(row instanceof JSONObject)) continue;
Map<Object, Object> values = new HashMap<>();
for (Object item : ((JSONObject) row).getJSONArray("item")) {
if (!(item instanceof JSONObject)) continue;
values.put(((JSONObject) item).get("name"), ((JSONObject) item).get("value"));
}
result.getJSONObject("Details").getJSONArray("row").put(values);
}
// Now result is in your format
I'm using a Map<String, Map> resultMap having values like this:
[
{main={group={street={cnt=Burundi, zip=123}, code=asd, subtype={OrgType=1,2}}}},
{main={info={text=bbb}}},
{main={group={subId=5, attrib={attribId=1,2}}}}
]
I have to create a JSON out of those Maps that should look like this:
{ "main": [
{
"group": {
"street": {
"cnt": "Burundi",
"zip": "123"
},
"code": "asd",
"subtype": {
"OrgType": "1,2"
},
"subId": "5",
"attribId": "1,2"
},
"info": {
"text": "bbb"
}
}
]
}
Any idea how could I merge those Maps doing a GSON.toJson(resultMap); to obtain this JSON ?
I tried to merge the Map
public String produceJsonFromMap(Map<String, Map> initialMap) {
Map<String, Object> resultMap = new HashMap<>();
for(Map map: initialMap.values()) {
resultMap.putAll(map);
}
return GSON.toJson(resultMap);
}
But this overwrites my previous maps and I don't know how can I obtain the desired merged map...
I have a service that returns me a response that has the below object
{
"features": [
{
"name": "climateControl"
},
{
"name": "drivingControl"
},
{
"name": "breakeControl",
"type": [
{
"name": "safety"
}
]
},
{
"name": "seatAdjustments",
"type": [
{
"name": "motion"
}
]
},
{
"name": "enginePower",
"type": [
{
"name": "motion"
}
]
}
]
}
Now I need to extract the feature names that are either null or doesn't have any type with name "safety"
I can write something like below
List<Features> features = service.getFeatures();
List<String> refinedList = new ArrayList<>();
for(Feature feature:features){
if(feature.getType==null || feature.getType().getName().equalsIgnoreCase("safety") )
{
refinedList.add(feature.getName());
}
}
Looking for a way to do the same using java streams.
You can use filter for the if conditions and map to getName, then collect as:
List<String> refinedList = features.stream()
.filter(feature -> feature.getType == null || feature.getType().getName().equalsIgnoreCase("safety"))
.map(feature -> feature.getName())
.collect(Collectors.toList());
I am consuming an external web service and receiving a JSON response. In this response, there is an object "entities" containing multiple arrays in it, with a name before each array.
I want to add the name before the array in the array object itself.
For example this is the original response:
{
"entities": {
"entity": [
{
"confidence": 1,
"value": "user",
"type": "value"
},
{
"confidence": 1,
"value": "insurance form",
"type": "value"
}
],
"ui_page_step": [
{
"confidence": 1,
"value": "step 1",
"type": "value"
}
],
"userrole_ano": [
{
"confidence": 0.96535832252792,
"value": "anonymous user"
}
]
}
}
I need to convert it to:
{
"entities": {
"entity": [
{
"name": "entity",
"confidence": 1,
"value": "user",
"type": "value"
},
{
"name": "entity",
"confidence": 1,
"value": "insurance form",
"type": "value"
}
],
"ui_page_step": [
{
"name": "ui_page_step",
"confidence": 1,
"value": "step 1",
"type": "value"
}
],
"userrole_ano": [
{
"name": "userrole_ano",
"confidence": 0.96535832252792,
"value": "anonymous user"
}
]
}
}
How can I convert the original response to the desired one in Java?
Here is a (one of several possible) solutions:
It uses Jackson library to parse the Json into a java Map that is (relatively) easier to navigate and modify than JSONObject.
the method putCollectionNamesInsideEntries() assumes one root "entities" entry that has several collections as values. it iterates over all of them, adding "name" entry with name of collection.
the map is serialized back to Json (and sent to System.out)
import java.io.*;
import java.nio.file.*;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTest
{
public static void main(String[] args) {
try (InputStream is = Files.newInputStream(Paths.get("C:/temp/test.json"))) {
ObjectMapper mapper = new ObjectMapper();
// deserialize json into map
Map<String, Object> map = (Map<String, Object>)mapper.readValue(is, Map.class);
putCollectionNamesInsideEntries(map);
// serialize map into json
mapper.writeValue(System.out, map);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void putCollectionNamesInsideEntries(Map<String, Object> map) {
// get root "entities" entry
Map<String, Object> entitiesMap = (Map<String, Object>)map.get("entities");
for (Map.Entry<String, Object> entitiesEntry : entitiesMap.entrySet()) {
// iterate over collection entries
if (entitiesEntry.getValue() instanceof Collection) {
Collection coll = (Collection)entitiesEntry.getValue();
// iterate over entries in collection
for (Object collEntry : coll) {
if (collEntry instanceof Map) {
// add "name" with ame of collection (key entry under "entries")
((Map<String, Object>)collEntry).put("name", entitiesEntry.getKey());
}
}
}
}
}
}
Here is the json string from which i have to retrieve the element value
{ "search": { "entry": [
{ "d": "op=example.com",
"at": [
{ "name": "id", "value": [ "786786876" ] },
{ "name": "name", "value": [ "usaduas" ] }]
},
{ "d": "op=example.com",
"at": [
{ "name": "id", "value": [ "786876876" ] },
{ "name": "call", "value": [ "gyudyusg" ] }]
},
{ "d": "op=example.com",
"at": [
{ "name": "call", "value": [ "hsadkjhsakjdh" ] },
{ "name": "id", "value": [ "768768768" ] }]
}
I want to retrieve the text from attribute or node "name" : "call". I want to retrieve this value using jsonPath.
Thanks in advance.
please try one of these as per your understanding. These two are most convenient and highly used API to Serialize or Deserialize the JSONObject google gson API tutorial-convert-java-object-to-from-json
OR
Google Json simple API example-read-and-write-json