I am migrating from snakeyaml and a feature snakeyaml had is that it automatically wrote the object type in the output YAML so that deserialization would be transparent and easy. I cannot seem to find the same feature in Jackson Databind.
If I merely specify Object.class, I get a LinkedHashMap which is to be expected. Additionally, for this to work, I would have to see the class type in the JSON and I haven't found a native way to do that.
Is this required?
If I understand the problem correctly perhaps you are looking for JsonTypeInfo
From the docs
// Include Java class name ("com.myempl.ImplClass") as JSON property "class"
#JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="class")
I ended up prepending the class name before the actual object data and then split that out prior to actually deserializing the data back into an object which is what snakeyaml does automatically. I was hoping to do this automatically in Jackson though.
Related
I have some incoming JSON (the field-order of which is not my choice) that embeds a dependent pair:
{
"data": {...},
"evt": "READY",
...
}
and what type I should read data into depends on the value of evt. With just a JsonParser this is impossible because there's no way to store data for later so that it can be returned to once evt is reached.
All of the data I'm parsing (unfortunately) already exists in a ByteBuffer, so is there a better interface to use than JsonParser? I don't want to bring in any more dependencies than jackson-core if it can be helped.
Looks like there is no simple way to achieve this without any additional dependencies.
I suppose, you need to add at least jackson-databind (and also jackson-annotations if not added automatically via Maven/Gradle).
Then you can use an ObjectMapper as an ObjectCodec for the parser and parse the complete JSON either into a TreeNode structure that can be partically parsed later into the correct type or - if you have objects for all types of data - you maybe can directly parse the complete object with matching data type. If needed, a custom ObjectCodec could be implemented to first collect the unknown data and then later process it when the type is known, but implementing an ObjectCode does not seem to be that easy.
Instead of Jackson you could use GSON which can either parse the data into the complete object structure or a generic JSON object tree without any additional dependencies.
If you really cannot add additional dependencies, then you could implement a SAX-XML-Parser-like logic using JsonParser.nextToken, but I suppose that would require a lot of custom logic.
I'm using Java jackson for dynamic serialization and deserialization to/from json.
I want to have a custom annotation #JsonDebug, which will basically turn on/off the serialization of
field etc. depending on a static variable debugMode. The idea is that if an enum key is tagged with the annotation,
it shouldn't be useable while serialization/deserialization process is on.
The problem is that the only way I find doing it is by either implementing custom serializer/deserializer for the enum I want, which is not a general solution or by overriding the existing Enum serialization/deserialization process which is kind of a overkill for a single annotation processing. I tried using AnnotationIntrospector and override behavior of hasIgnoreMarker which is the way it works for fields, but it doesn't ignore enum keys. I thought mixin annotations might be the way to go, but they only work for specified classes with specified field names. I found out that even with ignore annotations on keys, they still serialize/deserialize to/from json.
.
What serializer is Entity.json(T entity) using to serialize/deserialize objects? Is it somehow possible to use a custom serializer?
In my case the serialization is wrong because my object contains fields with the Guava Optional data type and absent values are returned as {"present":false} instead of null.
The JSON serializer isn't specified by JAX-RS, it depends on your configuration. For example, Jersey JAX-RS allows several (https://jersey.java.net/documentation/latest/media.html), including
MOXy
Java API for JSON Processing (JSON-P)
Jackson
Jettison
But a better solution is not to use Optional (either Guava or Java 8) for fields. See http://blog.joda.org/2014/11/optional-in-java-se-8.html
My only fear is that Optional will be overused. Please focus on using
it as a return type (from methods that perform some useful piece of
functionality) Please don't use it as the field of a Java-Bean.
Not directly solving your problem. I suggest you use Googles Gson as a parser. It is very flexible and configurable.
Tutorial
It also skips blank fields so the json size is not too large.
I am struggling to find a library that will serialise a simple graph of Java objects to/from JSON (no need for circular refs or anything). I don't want to have Java class names in the output but including an extra "#type": "foo" property is fine. It must work with untyped collections and maps. I expect to have to do something like mapper.registerType(MyClass.class, "foo") to specify the type mappings but the library must take it from there. Anyone know of such a thing?
Jackson should be able to handle what it is that you are trying to do. Check out the examples from this link, most specifically #4 for polymorphic type deserialization
Jackson
Polymorphic Type Handling
Examples
Take a look at Genson it provides full databinding support, with polymorphic and untyped objects and has many other features.
// this defines aliases for classes, if you don't care of class names being
// serialized then just enabled type ser/deser using builder.setWithClassMetadata(true)
Genson genson = new Genson.Builder()
.addAlias("person", Person.class)
.addAlias("other", Some.class)
.create();
// serialize using with type information
String json = genson.serialize(object);
// deserializing to an unkown type based on the type information in the json string
genson.deserialize(json, Object.class);
Do you search something like this?
http://code.google.com/p/json-io/
json-io consists of two main classes, a reader (JsonReader) and a
writer (JsonWriter). There is a 3rd rigorous test class
(TestJsonReaderWriter). json-io eliminates the need for using
ObjectInputStream / ObjectOutputStream to serialize Java and instead
uses the JSON format.
...
Usage
json-io can be used directly on JSON Strings or with Java's Streams.
I am using Axis to call a SOAP-based web service. I'm then trying to serialize the returned remote object as JSON, using the Google Gson library.
The serialization to JSON fails, with Gson complaining that "there are multiple elements with the name __equalsCalc()).
When I inspect the returned object in my IDE (Eclipse), I can see that this is true -- the returned object has three members called __equalsCalc() and another three called __hashCode.
I know from looking around that these are added by WSDL2Java (I think) in order to avoid recursion. My question is, why are there THREE of each? And how can I get the serializer to ignore these? They're not actually part of the object's definition (it's called a RemoteProject, for reference). Can I do something hackish like cast the RemoteProject to a RemoteProject to get it to drop those members?
This turns out to be not too hard to solve. I have multiple copies of the same instance var because the class being serialized is shadowing fields of the same name from superclasses. Since I don't care about these fields, the best approach in Gson is to write a custom ExckusionStrategy which can selectively ignore fields based on their name:
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/ExclusionStrategy.html
I don't know GSon.
With Jackson, you can annotate properties (i.e - fields that have getters/setters according to Java bean convention) with #JsonIgnore.
This way you can prevent issues like recursion/no matching setter or getter and so on...
Try to find out if you have the same at GSon or use Jackson.