Patrick
Patrick

Reputation: 12744

How to get JSON String with Subdomain in Java Map at Spring MVC Controller

I'm trying to receive a JSON String with subdomain to a Java Map at Spring MVC Controller.

Let's say I have this JSON at the JavaScript part:

var contract = {dateFrom:someDate,
           dateTo:someDate, 
           season: {seasonCode:someString}}

The JSON is sent as GET Ajax call.

The Controller looks like this:

@RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=application/json")
public ResponseEntity<String> getVertagFromSearch(@RequestParam Map<String, Object> allRequestParams, ModelMap model){

The output of the Map looks like this:

{dateFrom=02-07-2014, dateTo=02-07-2014, season[seasonCode]=SO03}

The GET Request looks like this:

http://localhost:8080/contracts/?dateFrom=02-07-2014&dateTo=02-07-2014&season%5BseasonCode%5D=SO03

I want to parse this Map into my contract domain object. But with this structure it doesnt work. Without a subdomain(season) it worked.

Thanks in advance!

Update 1

Sending as an object it looks like this: (output Browser)

Object { dateFrom: "09-07-2014", dateTo: "08-07-2014", season: Object }

Sending after JSON.stringify it looks like this:

"{"fromDate":"09-07-2014","dateTo":"08-07-2014","season":{"saiCode":"SO03"}}"

In this case I think the probem are the double quotes at the beginning and at the end.

Upvotes: 0

Views: 672

Answers (1)

Pablo Lozano
Pablo Lozano

Reputation: 10342

I think the best two options are:

1) Modify your JS object to have only simple objects. If you look at your request URL before your update, you had:

{your IP:port}/contracts/?dateFrom=02-07-2014&dateTo=02-07-2014&season%5BseasonCode%5D=SO03

That is not JSON at all, is a simple request with three parameters:

 dateFrom = 02-07-2014 
 dateTo = 02-07-2014
 season%5BseasonCode%5D= SO03   // %5B and %5D are '[' and ']' escaped

So your javascript is transforming a JS object (not JSON) in plain parameters.

2) Send a parameter, a string, with your JSON structure and then use some JSON library to parse it:

http://localhost:8080/contracts/?myJson=<JSON_String>

and then modify your controller as:

@RequestMapping(value="/", method=RequestMethod.GET, headers="Accept=text/plain")
public ResponseEntity<String> getVertagFromSearch(@RequestParam String myJson, ModelMap model){
    JSONObject myJSON= new JSONObject (myJson);
    ...
}

Usually sending a JSON is easier with a POST (just adding it to the body), but as your request seems to ask for data, a POST request is not a good idea. Most of the rest APIs use the first approach, JSON tends to be part of a response more than part of a GET request.

Upvotes: 1

Related Questions