Search code examples
jacksonjson-deserialization

RestTemplate - Jackson Deserializer


I am trying to consume a REST Service using RestTemplate. I am having trouble deserializing the JSON response. I am using a custom Deserializer and my JSON has 3 nodes, but it looks like only one is reaching the deserializer. Below are more details.

Below is the response JSON:

{
    "Hello": {
        "Hi": "Name1",
        "Call": "PhoneNumber1"
    },
    "Hello": {
        "Hi": "Name2",
        "Call": "PhoneNumber2"
    },
    "Hello": {
        "Hi": "Name3",
        "Call": "PhoneNumber3"
    }
}

I am using a custom deserializer on the Response Class for attribute Hello using @JsonDeserializer.

When i do a readTree like below:

JsonNode node = jp.getCodec().readTree(jp);

it reaches the deserialize method, it looks like it is having only one node instead of 3 like below. Sometimes it has the first node and sometimes the last. What could be going wrong here?

Thanks in advance for looking at this question and helping out!

ANSWER: As others mentioned, this JSON is invalid and hence Jackson is not able to deserialize it. I had to get the response as a String and then deserialize manually.


Solution

  • JsonNode is a superclass without specific content behavior. In your example you should get an ObjectNode but as your properties all have the same name only one "Hello" property will remain. readTree() is a generic method which do auto cast to your needed return type if possible.

    If you really need this you have to move your JSON to an array structure:

    // you will get one ArrayNode containing multiple ObjectNode
    [
      {
        "Hello": {
          "Hi": "Name1",
          "Call": "PhoneNumber1"
        }
      },
      {
        "Hello": {
          "Hi": "Name2",
          "Call": "PhoneNumber2"
        }
      },
      {
        "Hello": {
          "Hi": "Name3",
          "Call": "PhoneNumber3"
        }
      }
    ]
    

    or

    // you will get one ObjectNode containing one property with an ArrayNode
    {
      "Hello": [
        {
          "Hi": "Name1",
          "Call": "PhoneNumber1"
        },
        {
          "Hi": "Name2",
          "Call": "PhoneNumber2"
        },
        {
          "Hi": "Name3",
          "Call": "PhoneNumber3"
        }
      ]
    }