jeudi 2 avril 2015

Error while serializing object to json Jackson

I need a json output in the format



{
main:[
{
"tag1" : "value1",
"tag2" :"value2",
"tag3" :[
{
"subTag1" :"value3",
"subTag2" :"value4",
"subTag3" :"value5
},
{
"subTag1" :"value3",
"subTag2" :"value4",
},
{
"subTag1" :"value3",
"subTag3" :"value5
}
]
},
{
"tag1" : "value1",
"tag2" :"value2",
"tag3" :[
{
"subTag1" :"value3",
"subTag2" :"value4",
"subTag3" :"value5
},
{
"subTag1" :"value3",
"subTag2" :"value4",
},
{
"subTag1" :"value3",
"subTag3" :"value5
}
]
}
]
}


My java class has objects of the form



public class MainObject{
Map<String,Object> tagValueMap = new HashMap<String,Object>();
}


I would like to keep the MainObject class generic. This implementation is throwing an error when I try to create json using Jackson in Spring. An error is thrown by jackson ObjectMapper called from



org.springframework.http.converter.json.MappingJacksonHttpMessageConverter


writeInternal() method which says



org.codehaus.jackson.map.JsonMappingException:
java.util.LinkedHashMap cannot be cast to java.lang.String


Why is it trying to cast the object to a string rather than reading it as hashmap? How can I avoid this error?


I am aware of specifically mentioning each field in the MainObject class for serialising an object. But How can I achieve the same with a generic class which will accept both string elements and array elements in the json object.


Thanks


Aucun commentaire:

Enregistrer un commentaire