简体   繁体   English

杰克逊:避免反序列化某些字段,但不要忽略它们

[英]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. 我需要携带所有json数据(存储它们,记录日志,返回数据),但我永远不会从代码访问它们。 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

Take a look at: JsonProperty.Access 看看: 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 READ_ONLY-访问设置,意味着该属性只能在进行序列化时读取,而在写入期间不能写入(设置)
    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 READ_WRITE-访问设置,这意味着将同时访问该属性以进行序列化(将值写为外部表示形式)和反序列化(从中读取值
    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. WRITE_ONLY-访问设置,这意味着只能为反序列化写入(设置)该属性,而在序列化时不会读取(获取)该属性,即,该属性的值不包括在序列化中。

So in your case you could use it like this: 因此,在您的情况下,您可以像这样使用它:

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

You can use the type JSONObject for the Json field. 您可以将JSONObject类型用于Json字段。

private JSONObject notImportantJsonGarbage;

And when you need to read that, you can convert it to a String (or other type). 并且当您需要阅读该内容时,可以将其转换为String(或其他类型)。 You can use jackson or gson libraries to achieve that. 您可以使用jacksongson库来实现。

Note that when you convert the JsonObject back to String , the resulting string might have the quotes escaped. 请注意,当您将JsonObject转换回String ,结果字符串可能会使引号转义。

Using JSONObject also solves your requirement of 'must be a valid json object'. 使用JSONObject还可以解决“必须是有效的json对象”的要求。

您可以对要忽略的属性使用注解@JsonIgnore

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM