hkievet
hkievet

Reputation: 169

Groovy JsonSlurper Issue involving commas in JSON

I have some JSON coming into my controller, call it params.formData, it looks like this:

'{"year":"2014","resource":["Smith, John","Foo, Bar"]}'

My code to parse it:

....
def slurper = new JsonSlurper()
def data = slurper.parseText(params.formData)
...

data looks like:

[resource:["Smith", "John", "Foo", "Bar"], year:"2014"]

Notice that there were two JSON entries, and the parser made it into an array of four entries. I want it to look like this:

[resource:["Smith, John", "Foo, Bar"], year:"2014"]

Does anyone know how to handle this situation?

Upvotes: 2

Views: 283

Answers (3)

Roy Willemse
Roy Willemse

Reputation: 126

Definitely a Map rendering "optical illusion"

data.resource.each {
    println it
}

Smith, John
Foo, Bar

Upvotes: 0

Dónal
Dónal

Reputation: 187499

I can't reproduce this behaviour. Run this code in the Groovy console

import groovy.json.JsonSlurper

def json = '{"resource":["Smith, John","Foo, Bar"]}'
def slurper = new JsonSlurper()
def data = slurper.parseText(json)

assert data.resource.size() == 2

The assertion passes, indicating that there are 2 entries. Why do you think there are four?

Upvotes: 1

tim_yates
tim_yates

Reputation: 171084

I don't think it does.

assert data.resource.size() == 2

Should prove me right ;-)

My guess is the output of printing data:

[resource:[Smith, John, Foo, Bar], year:2014]

Confused things. It looks like 4, but it's 2

Upvotes: 2

Related Questions