I have a JSON as follows
JavaScript
x
[
{
"a": "John",
"id": "6",
"c": "val1"
},
{
"a": "Jack",
"id": "6",
"c": "val2"
},
{
"a": "Joe",
"id": "6",
"c": "val3"
}
]
I need to convert it into a Map<String, String> such that the values of the fields ‘a’ become the key and the values of the fields ‘c’ become the value in the Map.
In other words, my Map should look like the below:
JavaScript
John:val1
Jack:val2
Joe:val3
What is the shortest way to do this?
Also, I was wondering if in any way RestAssured GPath can be leveraged here
Something like this –
JavaScript
new JsonPath(jsonPayload).getString("findAll { json -> json.id == '6' }.a");
Advertisement
Answer
You can use jackson
for example:
JavaScript
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
I would create a wrapper for the resulting Map
and a custom deserializer.
JavaScript
@JsonDeserialize(using = MapWrapperDeserializer.class)
public class MapWrapper {
private final Map<String, String> map;
public MapWrapper(Map<String, String> map) {
this.map = map;
}
public Map<String, String> getMap() {
return this.map;
}
}
The deserializer:
JavaScript
public class MapWrapperDeserializer extends StdDeserializer<MapWrapper> {
public MapWrapperDeserializer() {
super(MapWrapper.class);
}
@Override
public MapWrapper deserialize(JsonParser parser, DeserializationContext context) throws IOException {
JsonNode array = parser.getCodec().readTree(parser);
int size = array.size();
Map<String, String> map = new LinkedHashMap<>(size);
for (JsonNode element : array) {
String key = element.get("a").asText();
String value = element.get("c").asText();
map.put(key, value);
}
return new MapWrapper(map);
}
}
A simple test:
JavaScript
public class Temp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
InputStream dataStream = getInputStreamOrJsonString();
MapWrapper wrapper = mapper.readValue(dataStream, MapWrapper.class);
System.out.println(wrapper.getMap());
}
}