9

We have a Spring binding which is converting strings to Lists, using default converters available with Spring.

For example if we have a, b, c pushed from the form then the controller gets a List with elements:

  1. a
  2. b
  3. c

We don't have to do anything special in our code.

I have a problem dealing with commas in my data. If I submit a, x,z, b , c here x,z is actually a single String, but the Spring converter does not know that and assumes that it's a delimiter and makes up the List like this:

  1. a
  2. x
  3. y
  4. b
  5. c

Now I come to my questions:

  1. Can I escape , (comma) in my data when submitting the form?
  2. If I have to register a custom converter, will I affect the default behavior for specific data character escaping?
  3. Can I control the order of converters?
  4. How do I tell my converter to pick up for this kind of data alone ?
  5. If I have to create a custom converter, can I have a custom annotation to say that my converter should work for only the fields that got my annotation?
Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
Shiv
  • 521
  • 2
  • 11
  • 27
  • Apologies for the significant rewrite.. it's an interesting question and I was worried people weren't reading it because of the phrasing. – Paul Hicks May 16 '14 at 03:34
  • Please show your context config, and java code (if there is any). – Eugene May 19 '14 at 22:57
  • There is nothing fancy about code its just a normal controller which binds to a String array or a collection list – Shiv May 20 '14 at 01:31

1 Answers1

1

I think there is actually no way to escape comma in spring properties that are converted to a list/array by spring (e.g. by means of a ConfigurationProperties class or similar).

Maybe there is some obscure way using SpEL or something but I found it easier to specify list properties in the "index" notation (not sure how this is called correctly).

Your example translates like this

# results in ["a", "x", "z", "b", "c"]
some.property.list=a, x,z, b, c
# results in ["a", "x,z", "b", "c"]
some.property.list[0]=a
some.property.list[1]=x,z
some.property.list[2]=b
some.property.list[3]=c

The obvious drawback however is that you need to maintain the index manually. But usually you will only have a limited number of entries in such a configurable list (at least from my hitherto experience).

Another way would of course be switching to YAML configuration instead of properties:

some:
  property:
    list:
    - "a"
    - "x,z"
    - "b"
    - "c"
dpr
  • 10,591
  • 3
  • 41
  • 71