Cony
Cony

Reputation: 223

Deserialize JSON to Map<String,String> using jackson databind

I'm using spring 4.0.5.RELEASE and jackson-databind 2.2.3 in my web application. When sending this JSON:

{"keyField1":"57579","keyField2":"sdf","someField":"sdasd","parameters":[{"parameterName":"dfgdfg","parameterValue":"sdf"},{"parameterName":"erwer","parameterValue":"sdfsdf"}]}

to the controller all I get is a HTTP 400 Bad Request at browser, I don't see any error at local websphere log, but after some tests I saw that the problem is with deserialization of the JSON array to the map. I never get into the save method at the controller. Tried some annotation like @JsonDeserialize(as=HashMap.class) without success. How can I resolve this?

My POJO:

class MyClassId implements Serializable {
private static final long serialVersionUID = 5022985493208399875L;
String keyField1;
String keyField2;
}

@Entity
@IdClass(MyClassId.class)
public class MyClass {
@Id
String keyField1;

@Id
String keyField2;

String someField;

@ElementCollection
@MapKeyColumn(name="parameterName")
@Column(name="parameterValue", length=400)
Map<String, String> parameters;
... Getters and Setters ...

My controller:

@RestController
@RequestMapping("/myclass/**")
public class MyClassController {

@Transactional
@RequestMapping(value = "/save", method = RequestMethod.POST, consumes={"application/json"})
public @ResponseBody ServiceResponce<MyClass> save(@RequestBody MyClass processToSave) {
    ... Code ...
}
}

Upvotes: 0

Views: 2994

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202316

I see two solutions to your problem:

Hope it helps you, Thierry

Upvotes: 1

user1907906
user1907906

Reputation:

In the JSON, parameters is not an object but an array of objects:

"parameters":[{"parameterName":"dfgdfg","parameterValue":"sdf"}, ...

You can not map this on a

Map<String, String> parameters;

Use at least

List<Map<String, String>> parameters;

Upvotes: 1

Related Questions