Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force jackson mapper to always add class type on writeValue without annotations

Tags:

json

jackson

Is it possible to configure jackson to always add the type of the serialized object to the generated json output.

For example:

package org.acme;

class ClassA
{
    String a;
    String b;
}

and I want the generated json to be: ["org.acme.ClassA",{"a":"str1","b":"str2"}]

like image 261
jacob Avatar asked Jan 16 '23 11:01

jacob


2 Answers

You can do that with enableDefaultTyping() of the ObjectMapper

e.g.

mapper.enableDefaultTyping(DefaultTyping.OBJECT_AND_NON_CONCRETE);

See ObjectMapper API

like image 123
Joseph Rajeev Motha Avatar answered Jan 18 '23 23:01

Joseph Rajeev Motha


If your are free to change from Jackson and do not especially need the format to match the one your are showing you can try Genson http://code.google.com/p/genson.

For example if your requirement is to be able to deserialize interfaces or abstract classes based on the original type of the object you serialized you can do:

interface Entity {}
static class Person implements Entity {}

Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
// json will be equal to {"@class":"my.package.Person"}
String json = genson.serialize(new Person());

// and now Genson is able to deserialize it back to Person using the information 
// in the Json Object
Person person = (Person) genson.deserialize(json, Entity.class);

Another nice feature is the ability to define aliases for your classes, so you show less information in the json stream but also this allows you to do refactoring without worring of existing json streams (for example if you store it in a database).

Genson genson = new Genson.Builder().addAlias("person", Person.class).create();
// json value is {"@class": "person"}
String json = genson.serialize(new Person());

Have a look at the wiki.

like image 21
eugen Avatar answered Jan 19 '23 01:01

eugen