I have a JSON like below:
{
"name": "John",
"age": 29,
"city": "Bangalore",
"country": "India"
}
But based on the request, I need to filter only the name and city. My response should be like the following:
{
"name": "John",
"city": "Bangalore"
}
How do we achieve this using Java code?
2
Answers
There are at least 3 ways to do it, which are library agnostic:
Request
) -> transform that into theResponse
object -> serialize the responseUse one class (see
Request
example above, but with more appropriate name) with custom serializer/deserializer. The deserializer will read all properties, the serializer will write only the ones you need –name
andcity
.Use the generic object –
Map<String, Object>
. Deserialize into aMap
-> remove properties you don’t need from it (age
,country
) -> serialize the map.There are more ways, which are specific to the json library used, but generally they will follow the same approach – read input -> either take only what you need or remove only what you don’t need -> write output.
All JSON libraries with query capability can do that, such as Josson.
https://github.com/octomix/josson
Output