user2880771
user2880771

Reputation: 127

Spring Boot JSON Post 400 Error

I'm having trouble posting a JSON array to a Spring Boot @RequestMapping Rest controller. Get 400 Bad Request. Any suggestions how to correct?

JQuery .ajax post

var sData = ["15957.028", "16356.175", "16937.155", "17564.315", "17942.480", "17760.259", "16572.306", "16746.408", "17339.681", "17946.216"] 

$.ajax({
    type: "POST",
    url: "/regression", 
    data: JSON.stringify({"sdata": sData}),
    contentType: 'application/json',
    headers: { 'X-CSRF-Token': token },
    error: function(jqXHR, textStatus, errorThrown) {
          console.log(textStatus, errorThrown, jqXHR.error());
    },
    success: function(){

    }
});

@RestController

@RequestMapping(value="/regression", method = RequestMethod.POST)
public HashMap<String, String> results(@RequestBody List<String> series )  {

    HashMap<String, String> results = new HashMap<String, String>();

    return results;

}

Response Error

responseText: "{"timestamp":1424834682223,"error":"Bad Request","status":400,"message":""}"

Upvotes: 2

Views: 5250

Answers (2)

Srini Kancharla
Srini Kancharla

Reputation: 120

The sData you are trying to post is not in JSON format, where as you are trying to post it as JSON

data: JSON.stringify({"sdata": sData}),
    contentType: 'application/json',

Hence the 400 error.

Proper JSON format example:

{ "firstname" : firstname, "lastname" : lastname, "email": email, "phone": phone, "company": company};

Upvotes: 0

iamiddy
iamiddy

Reputation: 3073

You will need to wrap the List into another class like below

class SeriesWrapper{
  @Getter @Setter private List<String> series;
}

Your Controller becomes

@RequestMapping(value="/regression", method = RequestMethod.POST)
public HashMap<String, String> results(@RequestBody SeriesWrapper series )  {

    HashMap<String, String> results = new HashMap<String, String>();
    return results;

}

and your sData

var sData = {series : ["15957.028", "16356.175", "16937.155", "17564.315", "17942.480", "17760.259", "16572.306", "16746.408", "17339.681", "17946.216"]};

Upvotes: 1

Related Questions