简体   繁体   中英

Jackson annotation or method to URL encode/decode during serialization?

I'm wondering if there's an easy way to URL encode/decode when serializing and deserializing objects in Jackson. The reason for this would be to ensure that incoming fields that are going to be indexed in Riak do not contain illegal characters.

For example I have the following class (in Scala):

case class Client(
  @(JsonProperty@field)("guid")
  @(RiakKey@field)
  val guid: String,

  @(JsonProperty@field)("name")
  @(RiakIndex@field)(name = "name")
    val name: String,

  @(JsonProperty@field)("address")
    val address: String,

  @(JsonProperty@field)("contact")
    val contact: String,

  @(JsonProperty@field)("phone")
    @(RiakIndex@field)(name = "phone")
    val phone: String,

  @(JsonProperty@field)("suspended")
  val suspended: Boolean=false,

  @(JsonProperty@field)("created")
  val created: Date=now,

  @(JsonProperty@field)("updated")
    val updated: Date=now

)

So on the name field, I might have a space between a name which is part of the Riak Index. It will produce the following error when I go to store the JSON object in Riak:

Caused by: java.net.URISyntaxException: Illegal character in path at index 82: http://db2.3tierlogic.com:8098:8098/buckets/accounts-client/index/name_bin/Calgary Flames
        at java.net.URI$Parser.fail(URI.java:2810)
        at java.net.URI$Parser.checkChars(URI.java:2983)
        at java.net.URI$Parser.parseHierarchical(URI.java:3067)
        at java.net.URI$Parser.parse(URI.java:3015)
        at java.net.URI.<init>(URI.java:577)
        at java.net.URI.create(URI.java:839)
        ... 105 more

Is there an annotation or a very simple method of URL encoding and decoding that field on the fly?

The easy way is to specify which serializer/deserializer you would like to use

@JsonSerialize(using=classOf[YourSerializer])
@JsonDeerialize(using=classOf[YourDeserializer])
var customEncodedProperty: String = _

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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