4

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?

crockpotveggies
  • 12,682
  • 12
  • 70
  • 140

1 Answers1

5

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 = _
jdevelop
  • 12,176
  • 10
  • 56
  • 112
  • Ah ok, didn't think it would be that simple :) Thanks! – crockpotveggies Feb 20 '13 at 23:26
  • Any idea if `JsonSerialize` was moved outside the annotation package? Getting a `not found: type JsonSerialize` on compile. My other annotations are working properly. *Edit* Maybe it's not in 2.0? – crockpotveggies Feb 21 '13 at 00:21
  • should be in com.fasterxml.jackson.databind.annotation, if you're using maven - then you need to include jackson-databind module – jdevelop Feb 21 '13 at 01:07