piotrek
piotrek

Reputation: 14540

Jackson: avoid deserialization of some fields but not ignoring them

i need to carry all the json data (to store them, log, return) but i will never access them from code. is there any way to avoid deserializing them but still use them during serialization?

class MyObject {    
  int importantField; // i want this field to be properly deserialized
  String notImportantJsonGarbage; // i don't care what's here. it must be a valid json
}

So now i'd like to be able to deserialize it from

{"importantField":7, "notImportantJsonGarbage":{"key1":3, "key2":[1,2,3]}}

and later serialize it to the same string

UPDATE

i don't want to ignore this property. i need this data. but as a string, not fully deserialized object

i need to be able to do:

json1 -> object -> json2
json1 == json2

Upvotes: 2

Views: 4344

Answers (2)

gaganbm
gaganbm

Reputation: 2843

You can use the type JSONObject for the Json field.

private JSONObject notImportantJsonGarbage;

And when you need to read that, you can convert it to a String (or other type). You can use jackson or gson libraries to achieve that.

Note that when you convert the JsonObject back to String, the resulting string might have the quotes escaped.

Using JSONObject also solves your requirement of 'must be a valid json object'.

Upvotes: 1

Diyarbakir
Diyarbakir

Reputation: 2099

Take a look at: JsonProperty.Access

  • AUTO - Access setting which means that visibility rules are to be used to automatically determine read- and/or write-access of this property.

  • READ_ONLY - Access setting that means that the property may only be read for serialization, but not written (set) during
    deserialization.

  • READ_WRITE - Access setting that means that the property will be accessed for both serialization (writing out values as external representation) and deserialization (reading values from
    external representation), regardless of visibility rules.

  • WRITE_ONLY - Access setting that means that the property may only be written (set) for deserialization, but will not be read (get) on serialization, that is, the value of the property is not included in serialization.

So in your case you could use it like this:

@JsonProperty(access = Access.READ_ONLY)
private String notImportantJsonGarbage;

Upvotes: 7

Related Questions