How to serialize/deserialize the following object? - json

I have a java object as given below. How to serialize/deserialize with Jackson json?
public class Employee {
private String name;
List<Employee> friends;
}
The JSON:
{"friends":[{"name":"abc"}],[{{"name":"pqr"}}]}
My Implementation class:
public class EmployeeImpl implements Employee, Serializable {
private String name;
private List<Employee> friends;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<Employee> getFriends() { return friends; }
public void setFriends(List<Employee> friends) { this.friends = friends; }
}
Test Class:
public class Test {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"gangi\", \"friends\":[{\"name\":\"abc\"},{\"name\":\"pqr\"}]}";
Employee employee = deserializeJson(json, new TypeReference<EmployeeImpl>(){});
}
public static <T> T deserializeJson(String jsonData, TypeReference<T> typeRef) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.<T>readValue(jsonData, typeRef);
}
}
Exception stacktrace...
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException:
Can not construct instance of Employee,
problem: abstract types can only be instantiated with additional type information at
[Source: java.io.StringReader#68da4b71; line: 1, column: 29]
(through reference chain: EmployeeImpl["friends"]) at
org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163‌​)

Add following annotation to your Employee interface
`#JsonDeserialize(as=EmployeeImpl.class)`

Your json format is incorrect. See [http://www.json.org/] on how to define array/lists in json. Example for json building [http://java.dzone.com/tips/json-processing-using-jackson]

Related

Return an object using ResponseEntity with JSONObject as one of the object's field

My model looks like below, where in bookJson is a json object -
{
"name" : "somebook",
"author" : "someauthor"
}
public class Book{
private int id;
private JSONObject bookJson;
public int getId(){return this.id;}
public JSONObject getBookJson(){this.bookJson;}
public void setId(int id){this.id = id;}
public void setBookJson(JSONObject json){this.bookJson = json;}
}
JSONObject belongs to org.json package
When My RestController returns Book object in a ResponseEntity object , I get the error -
"errorDesc": "Type definition error: [simple type, class org.json.JSONObject]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
What is the best way to achieve this?
Can we not achieve this without having to have a model class with all fields of bookJson?
Figured this out.
Added JSONObject as a Map instead and used ObjectMapper to do all the conversions.
public class Book{
private int id;
private Map<String, Object>bookJson;
public int getId(){return this.id;}
public Map<String, Object>getBookJson(){this.bookJson;}
public void setId(int id){this.id = id;}
public void setBookJson(Map<String, Object> json){this.bookJson = json;}
}
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
} catch (IOException e) {
throw new JsonParsingException(e.getMessage(), e);
}
You need to return the ResponseEntity of List<Book> type.
public ResponseEntity<List<Book>> doSomething() {
return new ResponseEntity(bookList);
}

How to deserialize json to an abstract class in spring-boot

In my Application i have something like this.
public class Question{}
public class MCQ extends Question{}
public class TrueAndFalse Question{}
public class Match Question{}
and in my RestController i have a service that adds question.
#RequestMapping(value = "/game/question/add", method = RequestMethod.POST)
public Question addQuuestion(#RequestParam("gameId") long id, #RequestBody Question question)
But i get an error when i try to call this service as i send json file with different structures one for MCQ, TrueAndFalse and Match.
so is it possible to deserialize the received json to Question abstract class.
And thanks in advance.
You can create a custom deserializer which will create Question instances based on json payload properties.
For example if the Question class looks like this:
public class Question {
private final String name;
#JsonCreator
Question(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And sub-class TrueAndFalse:
public class TrueAndFalse extends Question {
private final String description;
#JsonCreator
TrueAndFalse(#JsonProperty("name") String name,
#JsonProperty("description") String description) {
super(name);
this.description = description;
}
public String getDescription() {
return description;
}
}
Then you can create a deserializer, which will create an instance of TrueAndFale sub-class by checking if it has description property:
public class QuestionDeserializer extends JsonDeserializer<Question> {
#Override
public Question deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
ObjectCodec codec = p.getCodec();
JsonNode tree = codec.readTree(p);
if (tree.has("description")) {
return codec.treeToValue(tree, TrueAndFalse.class);
}
// Other types...
throw new UnsupportedOperationException("Cannot deserialize to a known type");
}
}
And afterwards, make sure to register it on the object mapper:
#Configuration
public class ObjectMapperConfiguration {
#Bean
public ObjectMapper objectMapper() {
SimpleModule module = new SimpleModule();
module.addDeserializer(Question.class, new QuestionDeserializer());
return new ObjectMapper().registerModules(module);
}
}

Jersey - Serializing a POJO with json - nested objects will be ignored

HiAll,
i have the following problem in development branch:
If i use the jersey REST service to serialize the POJO containig a list of the nested other POJO, then this nested POJO will be NOT serialized. This problem is reproducible only in branch.
If i prototype using POJO structur liked in branch, i have no problem.
The Details:
The POJO (Domain):
public class Article {
private int id;
private int name;
// getter & setter
}
The POJO ( DTO)
public class DTO {
private List<Article> articles;
private String message;
public DTO {
articles= new ArrayList<>();
}
getArticles() {
return articles;
}
getArticlesCount() {
return articles.size();
}
public void getMessage() {
return message;
}
public String getMessage() {
return message;
}
....
}
It will be created the 1 article with id = 1 and name "firstArticle" the
The results of serialization after service call to find all articles:
in branch
*{"message":"1 article found","articlesCount":1
}*
in prototype
{
{"message":"1 article found","articlesCount":1[{"id":1,"name":"firstArticle"]}
}
i have no idia what's happened. I checked out all settings (web.xml, jersey version, etc.)
If you use Jackson JSON library, your POJO will be automatically handled by Jackson JSON lib to convert between JSON and POJO. You also need to add the following lines in your web.xml:
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
Then in your Jersey resource class, use #Produces and #Consumes annotation to indicate the data format is JSON:
#Path("/myResource")
#Produces("application/json")
public class SomeResource {
#GET
public String doGetAsJson() {
...
}
}
Follow the above answer to set up Jersey POJO mappping, and then try the following nested POJO example.
Article class:
public class Article {
private int id;
private String name;
public Article(int id, String name) {
this.id = id;
this.name = name;
}
//getter and setter ...
}
The Book class that contains the Article class:
public class Book {
private List<Article> articles;
private String message;
private int articleCount;
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
setArticleCount(articles.size());
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getArticleCount() {
return articleCount;
}
public void setArticleCount(int articleCount) {
this.articleCount = articleCount;
}
}
Finally in the Jersey resource class NestedPojoResource:
#Path("/nested-pojo")
public class NestedPojoResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Book getNestedPojo() {
Book book = new Book();
List<Article> articles = new ArrayList<Article>();
articles.add(new Article(1, "firstArticle"));
articles.add(new Article(2, "secondArticle"));
book.setArticles(articles);
book.setMessage(book.getArticleCount() + " articles found");
return book;
}
}
When you go to http://example.com/myappname/nested-pojo, you will see the correct JSON output which contains the nested POJO fields:
{"articles":[{"id":1,"name":"firstArticle"},{"id":2,"name":"secondArticle"}],"message":"2 articles found","articleCount":2}

Jackson Mapper Serialize/Deserialize ObjectId

My POJO is :
import org.jongo.marshall.jackson.id.Id;
public class User {
#Id
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I get user from mongo database and want to output him into a file with jackson mapper
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("c:/user.txt"), user);
and I get something like this in my file
{
"name" : "John",
"age" : 23,
"_id" : {
"time" : 1358443593000,
"inc" : 660831772,
"machine" : 2028353122,
"new" : false,
"timeSecond" : 1358443593
}
}
I need id field to be stored into a file as string because when i deserialize this object my id field in pojo looks something like this
{
"time":1358443593000,
"inc":660831772,
"machine":2028353122,
"new":false,
"timeSecond":1358443593
}
Any help will be apreciated
Answering my own question. Found solution here Spring 3.2 and Jackson 2: add custom object mapper
I needed custom object mapper and ObjectId serializer.
public class ObjectIdSerializer extends JsonSerializer<ObjectId> {
#Override
public void serialize(ObjectId value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value.toString());
}
}
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
SimpleModule module = new SimpleModule("ObjectIdmodule");
module.addSerializer(ObjectId.class, new ObjectIdSerializer());
this.registerModule(module);
}
}
I found an easy attempt using springboot 2.5.4.
Just by adding a Jackson2ObjectMapperBuilderCustomizer bean will do the trick.
#Configuration
public class JacksonMapperConfiguration
{
#Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> builder.serializerByType(ObjectId.class, new ToStringSerializer());
}
}
Here is a simple solution for serialization if you don't have a model for the object being stored:
client.getDatabase("db").getCollection("collection").find().onEach { it["_id"] = it["_id"].toString() }
"onEach" is a kotlin function. If you use Java, then change it to a simple foreach.
It's not efficient to iterate over the entire list just for the id. Only use it for small lists where performance is less important than short code.

Jackson JSON Deserialization of MongoDB ObjectId

Ok, so first off here's the JSON that's returning from my web service. I'm trying to deserialize it into pojos after an asynchronous query in a ResponseHandler in my Android ContentProvider.
{"exampleList" : [{
"locationId" : "00001" ,
"owners" : [
{
"paidID" : { "$oid" : "50a9c951300493f64fbffdb6"} ,
"userID" : { "$oid" : "50a9c951300493f64fbffdb6"}
} ,
{
"paidID" : { "$oid" : "50a9c951300493f64fbffdb7"} ,
"userID" : { "$oid" : "50a9c951300493f64fbffdb7"}
}
]
}]}
At first, I was confused about the problem I was seeing, since I use the same Jackson-annotated beans for my web service as I do in my Android app--but then I realized that the owners object was never getting sent in the sample JSON to my web service (it skips the POJOs on my web service and gets added into the documents in mongoDB through atomic updates from the DAO).
So OK. Up to now, Jackson wasn't having to handle the owners object, and now that it is it is choking on it, namely:
JsonMappingException: Can not deserialize instance of java.lang.String out of
START_OBJECT token at [char position where you can find "userID" and "paidID"]
through reference chain [path to my Jackson bean which contains the owners class]
My Jackson bean has a wrapper, which is what that "exampleList" is all about:
public class Examples extends HashMap<String, ArrayList<Example>> {
}
And then the actual Example class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Example implements Comparable<Example> {
#ObjectId #Id
private String id;
#JsonProperty(Constants.Example.location)
private String location;
#JsonProperty(Constants.Example.OWNERS)
private List<Owners> owners;
public int compareTo(Example _o) {
return getId().compareTo(_o.getId());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public List<Example.Owners> getOwners() {
return owners;
}
public void setOwners(List<Example.Owners> owners) {
this.owners = owners;
}
public Example() {
}
#JsonCreator
public Example(#Id #ObjectId String id) {
this.id = id;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Owners implements Comparable<Owners> {
#JsonProperty(Constants.Example.USERID)
private String userID;
#JsonProperty(Constants.Example.PAIDID)
private String paidID;
public Owners() {
}
public int compareTo(Owners _o) {
return getUserID().compareTo(_o.getUserID());
}
#ObjectId
public String getUserID() {
return userID;
}
#ObjectId
public void setUserID(String userID) {
this.userID = userID;
}
#ObjectId
public String getPaidID() {
return paidID;
}
#ObjectId
public void setPaidID(String paidID) {
this.paidID = paidID;
}
}
}
And finally, the code in the ResponseHandler where this is all failing (the 2nd line produces the JsonMappingException):
objectMapper = MongoJacksonMapperModule.configure(objectMapper);
mExamples = objectMapper.readValue(jsonParser, Examples.class);
I have a feeling the issue is that Jackson still doesn't know how to map those $oid, which are the mongoDB ObjectIds. The MongoJacksonMapper library is supposed to help that by providing the #ObjectId annotation and a way to configure the ObjectMapper to use that library, but it still isn't working. For some reason, it's still looking for the userID or paidID as a String, not an ObjectId. Any ideas?
Another alternative is
com.fasterxml.jackson.databind.ser.std.ToStringSerializer.
#Id
#JsonSerialize(using = ToStringSerializer.class)
private final ObjectId id;
This will result in:
{
"id": "5489f420c8306b6ac8d33897"
}
For future users: Use a custom jackson deserializer to convert $oid back to ObjectId.
public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {
#Override
public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode oid = ((JsonNode)p.readValueAsTree()).get("$oid");
return new ObjectId(oid.asText());
}
}
How to use:
ObjectMapper mapper = new ObjectMapper();
SimpleModule mod = new SimpleModule("ObjectId", new Version(1, 0, 0, null, null, null));
mod.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
mapper.registerModule(mod);
YourClass obj = mapper.readValue("{your json with $oid}", YourClass.class);
My code had at least two problems that were pretty tough to track down answers to online, so I'll make sure to link here. Basically, child classes need a constructor in the parent class that calls Jackson's readValue() to map the child. As far as mongoDB $oid's go, you should create a separate MongoId class to represent these mongo objects, and follow a similar pattern as with the child class to map the data when it comes in for deserialization. Here's a blog post I found that describes this well and provides some examples.
Jackson does not know how to serialize an ObjectId. I tweaked Arny's code to serialize any ObjectId and provide this working example:
public class SerialiserTest {
private ObjectMapper mapper = new ObjectMapper();
public static class T {
private ObjectId objectId;
public ObjectId getObjectId() {
return objectId;
}
public void setObjectId(ObjectId objectId) {
this.objectId = objectId;
}
}
#Test
public final void serDeser() throws IOException {
T t = new T();
t.setObjectId(new ObjectId());
List<T> ls = Collections.singletonList(t);
String json = mapper.writeValueAsString(ls);
System.out.println(json);
SimpleModule mod = new SimpleModule("ObjectId", new Version(1, 0, 0, null, null, null));
mod.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
mapper.registerModule(mod);
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, T.class);
List<?> l = mapper.readValue(json, type);
System.out.println(l);
}
}
public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {
#Override
public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode n = (JsonNode)p.readValueAsTree();
return new ObjectId(n.get("timestamp").asInt(), n.get("machineIdentifier").asInt(), (short) n.get("processIdentifier").asInt(), n.get("counter").asInt());
}
}
There's an even easier way documented here which was a lifesaver for me. Now you can use the ObjectId in Java but when you go to/from JSON it'll be a String.
public class ObjectIdJsonSerializer extends JsonSerializer<ObjectId> {
#Override
public void serialize(ObjectId o, JsonGenerator j, SerializerProvider s) throws IOException, JsonProcessingException {
if(o == null) {
j.writeNull();
} else {
j.writeString(o.toString());
}
}
}
And then in your beans:
#JsonSerialize(using=ObjectIdJsonSerializer.class)
private ObjectId id;
I did it like this:
#Configuration
public class SpringWebFluxConfig {
#Bean
#Primary
ObjectMapper objectMapper() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializerByType(ObjectId.class, new ToStringSerializer());
builder.deserializerByType(ObjectId.class, new JsonDeserializer() {
#Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
Map oid = p.readValueAs(Map.class);
return new ObjectId(
(Integer) oid.get("timestamp"),
(Integer) oid.get("machineIdentifier"),
((Integer) oid.get("processIdentifier")).shortValue(),
(Integer) oid.get("counter"));
}
});
return builder.build();
}
}