hiveship
hiveship

Reputation: 308

jackson unmarshalling problems

I am trying to deserialize a JSON String using Jackson 2 with RestAssured (java tool for IT tests).

I have a problem. The String I am trying to deserialize is :

{"Medium":{"uuid":"2","estimatedWaitTime":0,"status":"OPEN_AVAILABLE","name":"Chat","type":"CHAT"}}

There is the object type "Medium" at the begining of the String. This cause Jackson failing during deserialization:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Medium"

I've set the "IGNORE_ON_UNKNOWN_PROPERTIES" to false and then I got no exception during deserialisation. However, all of my properties are 'null' in java.

Response getAvailability -> {"Medium":{"uuid":"2","estimatedWaitTime":0,"status":"OPEN_AVAILABLE","name":"Chat","type":"CHAT"}}
@@@ MEDIUM name -> null
@@@ MEDIUM uuid -> null
@@@ MEDIUM wait time -> null
@@@ MEDIUM wait time -> null
@@@ MEDIUM status -> null

Does anyone can help me ? (note: I can't change my input JSON string).

Upvotes: 0

Views: 1216

Answers (3)

Bhokal
Bhokal

Reputation: 71

You need to put annotation @JsonRootName("Medium") on your bean class and configure object mapper to mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE).

Upvotes: 1

grizzly
grizzly

Reputation: 608

You need a way to remove the Object name that is the part of the input JSON. Since you cannot change the input string, Use this code to change this input string to a tree and get the value of "Medium" node.

ObjectMapper m = new ObjectMapper();
JsonNode root = m.readTree("{\"Medium\":{\"uuid\":\"2\",\"estimatedWaitTime\":0,\"status\":\"OPEN_AVAILABLE\",\"name\":\"Chat\",\"type\":\"CHAT\"}}");
JsonNode obj = root.get("Medium");
Medium medium = m.readValue(obj.asText, Medium.class);

Upvotes: 0

Pankaj Pandey
Pankaj Pandey

Reputation: 190

{
    "Medium": {
        "uuid": "2",
        "estimatedWaitTime": 0,
        "status": "OPEN_AVAILABLE",
        "name": "Chat",
        "type": "CHAT"
    }
}

as you can see uuid and other params are part of medium object , so class in which it can be deserialized is.

class Medium
{ 
   string name;
   // specify other params also.
}

class BaseObject
{ 
  Medium Medium;
}

and then use jackson.deserialize('json', BaseObject.class)

above i had given pseudo code

Upvotes: 2

Related Questions