Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape "," (comma) in Spring String to array or List conversion

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?
like image 813
Shiv Avatar asked May 16 '14 02:05

Shiv


1 Answers

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"
like image 162
dpr Avatar answered Oct 17 '22 07:10

dpr