I have some classes containing integer IDs, something like this:
class MyClass {
int myId;
// Other fields
}
I need a way to use a custom serializer only in certain cases (so that I cannot use #JsonAdapter) and of course I cannot generically use this serializer for all the integer values, because sometimes I want a sort of transformation of my ID (i.e. this is a web server response and I want to mask my ids so that they cannot be reused).
The full data model is quite complex and deep, and I annotated all the ID fields (even when they are collections) with a custom annotation #MyId. The point is that I don't find a valid way to say to a Gson instance "please, use this serializer for fields annotated with #MyId.
Do you have any ideas?
Related
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.
.
Is there a way to make #JsonIgnoreProperties target nested attributes?
Something like the code below:
public class ParentObject() {
#JsonIgnoreProperties({ "subAttributeA.subAttributeB.subAttributeC" })
private ChildObject attribute;
}
In this example, I want that subAttributeC is not included in the serialization of a ParentObject - but this same subAttributeC still need to be serializable in other scenarios.
If not possible with annotations, how to achieve this?
One possible way is to use #JsonSerialize with a custom serializer. This operates on a low abstraction level and you basically have to specify how to serialize every single attribute. There's an example here that uses a flat object, but given that JsonGenerator has methods like writeObject etc., I'm sure this can be used for a hierarchical structure, too.
If jackson is configured to not serialize null attributes:
objectMapper.setSerializationInclusion(Include.NON_NULL);
Then a simpler workaround is to set the unwanted attribute as null before returning it.
This is a kind of specific question and I couldn't get any information on this topic in the javadoc of Gson.
Currently, I'm trying to parse an Json(1){ "foo":"bar", "bar":"foo" } to an Object Entity. Normally I would map these values to the Entity Object with the fields foo and bar, however I'd like to be more independent from the API.
For (1) I'd have
public class Entity {
String foo;
String bar;
}
But if we test another Endpoint the resulting Json (2) would look like
{ "notFoo":"bar", "notBar":"foo" }
which makes my previous constructed Entity useless, and I'd need to create a new Class with the respective fields for that.
So my actual question is:
Is there a generic (more generic than my example) approach to
push the Json into a GenericEntity -> g.fromJson(response.getBody(),GenericEntity.class); that every field of the json will be successfully mapped, even when using different Endpoints?
Alternatively, are there other dependencies which support that out of the box?
You do not have a deserialisation problem, you have a problem of not knowing how to represent possibly heterogeneous data.
There is no point of saying it should be Object as it should definitely be some type downstream of Object, possibly more than one. Solve this problem first: define all types that you may want to use for all use cases and then you will most likely see how to solve the deserialisation problem.
Surely, for any JSON text defined between {...} you can always go for Map<String, Object> where Object is one of:
further Map<String, Object> where Object follows these rules
List<Object> where Object follows these rules
String
one of atomic types or their boxed values
With the above rules you can represent more or less everything and you can write Gson deserialisers to deliver you those types based on the JSON type of each node (while iterating via the JSON tree). However, it is not really clear what use could you make of such a heterogenous untyped data structure.
You can use the annotation #serializedName as written in Multiple GSON #SerializedName per field?. But the schema must be the same, you only have alternatives to key name.
I have a POJO that I want to Serialize differently based on a value of one of the properties.
Say, I have the POJO below. I want to include NULLs when "show" is true, and exclude NULLS when "show" is false. Be aware that the actual Object I am trying to Serialize has over 30 properties.
public class User {
#JsonIgnore
private boolean show;
private String name;
private Integer age;
...
...
}
I would like to know how to do that using Jackson. Do I have to implement my own JsonSerializer, or should I create a PropertyFilter? Or have I missed an out of the box feature?
You can write your own custom serialiser that takes care of the generation of null properties based on the show instance variable. For that you can create a ObjectMapper with NULL serialisation settings based on your show property and then delegate the serialisation to it.
I have a similar requirement and probably I'll be acquainting myself with the actual APIs of Object Mapper. I'll try to post the code for the above.
I was trying to implement the Map interface in Java utils, but instead I'll store the data in Mongo instead of in-memory. I also included generics in it for type safety. I wanted to handle all possible types - wrapper classes, custom classes which in turn can have multiple custom classes inside them and also potentially support something like:
Map<String, Set<Map<String, SampleObject>>> or Map<String, Set<SampleObject>>
I am using GSON to serialize the key and the values in JSONs and storing them and when fetching, deserialize them and return. This will work out for simple generic type parameters. But when it is nested, I have no idea how it will work out. Serialization will still work because I have the object at hand. But how do I know which class to return while deserializing?
Is there something else I can do?
I think it will be decided from your JSON key. For example, {"users" : {...}} means a collection of users and U can map it to Set<User> in your Java class. Also, here you can consider using JAXB.