0

I get two different kind of response json in two different scenario from single RESTful web service, how to parse the following response json with Jackson??

response:{
   result:"0"
}

and

response:{
   result :{
      fname: "abc",
      lname: "xyz"
   }
}
Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61

1 Answers1

0

You can deserialize as a JsonNode at the bare minimum and do some logic to determine the correct type. If you are looking for a specific solution please add some more details to your question. Here is something to get you started:

@Test
public void testDoubleResponseType() throws IOException {
    ImmutableList<String> jsonInputs = ImmutableList.of(
            "{\"result\": \"0\"}",
            "{\"result\": {\"fname\": \"abc\", \"lname\": \"xyz\"}}"
    );

    ObjectMapper om = new ObjectMapper();

    for (String jsonInput : jsonInputs) {
        JsonNode node = om.readValue(jsonInput, JsonNode.class);
        JsonNode result = node.get("result");
        if (result.isTextual()) {
            assertEquals("0", result.asText());
        } else if (result.isObject()) {
            NameResponse nameResponse = 
                om.readValue(result.toString(), NameResponse.class);
            assertEquals(new NameResponse("abc", "xyz"), nameResponse);
        } else {
            fail();
        }
    }
}

public static class NameResponse {
    private final String fname;
    private final String lname;

    @JsonCreator
    public NameResponse(@JsonProperty("fname") String fname,
                        @JsonProperty("lname") String lname) {
        this.fname = fname;
        this.lname = lname;
    }

    public String getFname() {
        return fname;
    }

    public String getLname() {
        return lname;
    }

    @Override
    public boolean equals(Object o) {...}
}
Sam Berry
  • 7,394
  • 6
  • 40
  • 58