skip to Main Content

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


  1. There are at least 3 ways to do it, which are library agnostic:

    1. Deserialize the data into a class (let’s say Request) -> transform that into the Response object -> serialize the response
    public class Request {
    
      private String name;
      private int age;
      private String city;
      private String country;
    }
    
    public class Response {
    
      private String name;
      private String city;
    }
    
    1. Use 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 and city.

    2. Use the generic object – Map<String, Object>. Deserialize into a Map -> 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.

    Login or Signup to reply.
  2. All JSON libraries with query capability can do that, such as Josson.

    https://github.com/octomix/josson

    Josson josson = Josson.fromJsonString(
        "{" +
        "    "name": "John"," +
        "    "age": 29," +
        "    "city": "Bangalore"," +
        "    "country": "India"" +
        "}");
    JsonNode node = josson.getNode("map(name, city)");
    System.out.println(node.toPrettyString());
    

    Output

    {
      "name" : "John",
      "city" : "Bangalore"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search