2

I am using Spring (with Jackson) and jQuery to pass a form as an object. My pojo includes nullable floats. However, when the fields are empty, Jackson throws an Exeption:

org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.lang.Float from String value '': not a valid double value

What do I have to do in order to allow nulls (or empty values in the form field)?

Thanks Er

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Ta Sas
  • 9,573
  • 15
  • 51
  • 73
  • Are you sure it's `null`, and not `""`? – Gabe Aug 20 '10 at 23:40
  • Actually, it is "", but what is the difference? Well, let's just say, I want to get along with no error when passing empty fields. – Ta Sas Aug 21 '10 at 00:18
  • 1
    What happens if the value in the JSON actually is `null` rather than `""`? Even in Javascript `null` and `""` are different values. – Stephen C Aug 21 '10 at 03:55
  • O.k., I understand that "null" means no value at all and "" is an empty string for which some memory was allocated and, perhaps, "\0" is stored. However, I had expected a concurrent framework to be sophisticated enough to deal with such an obvious requirement ... – Ta Sas Aug 28 '10 at 15:14

2 Answers2

1

By default Jackson does indeed only consider explicit JSON null as null value. But if coercion from empty String to null was desired, it's easy to add feature requests. It sounds like a nice improvement actually -- this is how open source projects are often improved, based on user's asking for things they think should be there, ways things should work.

On short term you could also register custom deserializer (http://wiki.fasterxml.com/JacksonHowToCustomDeserializers tells something about it, although is not a guide) that accepts empty String and produces null.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • Thanks, that is the solution I was looking for. Anyway, I understand how to create a custom serializer, but I don't know how to make it work with Spring. Any suggestion? – Ta Sas Aug 28 '10 at 15:16
  • I don't know details, but for value type you might be able to use @JsonDeserialize(using=...) for value type (if this is possible). If not, you need to be able to access ObjectMapper. There's tiny documentlet at http://wiki.fasterxml.com/JacksonHowToCustomDeserializers explains registration. But that too assumes full control which is probably not true with Spring. FWIW, feature request for handling empty Strings is (http://jira.codehaus.org/browse/JACKSON-349), and it will be part of 1.6 at least. – StaxMan Aug 30 '10 at 17:11
0

Your best bet is to check for empty string in the javascript code and pass null in that case.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Thanks, that will be my solution for prototyping. Yet, I do not believe that the client side is the right place for that conversion. – Ta Sas Aug 28 '10 at 15:15