Mattedatten
Mattedatten

Reputation: 69

Spring webservice won't read JSON

As editing a question didn't seem to bump it up for more answers, I'll continue asking in a new thread.

The thing is that I'm trying to set up a very basic web-service with Spring, to which I should be able to send JSON through Java.

But I'm very new to Spring, and web-services in general, so I don't know where to troubleshoot.

Old question: Getting a RESTful webservice with Spring to understand a JSON-string

Right now I have this in my controller

@RequestMapping(value = "/toggleB")
public @ResponseBody String sendCommand(@RequestBody Ident ident) {
//body
}

The Ident-class just has a String as variable, called IP.

Sending this String

 {"IP":"192.168.1.9"}

Gives the return code 400.

Thing is, I think there might be something wrong, or missing, in the build.gradle (or pom.xml). How is a correct Gradle/Spring project supposed to be organized as?

My main method is runnable, and looks like this:

 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 import org.springframework.boot.SpringApplication;
 import org.springframework.context.annotation.ComponentScan;

 @ComponentScan
 @EnableAutoConfiguration
 public class mainFile {
     public static void main(String[] args) {
         SpringApplication.run(mainFile.class, args);
     }
 }

I don't use any beans as configuration, might that be what fails my program?

Thanks again for replies! I hope I'm not breaking the rules by continuing my question like this, but I didn't know how to bump the old one up. Ah... The disadvantages of being completely new to a site, heh.

Upvotes: 0

Views: 81

Answers (1)

Sambhav Sharma
Sambhav Sharma

Reputation: 5860

If you're sending JSON in the request body, make it a POST or a PUT request, also add headers to accept json. Fetch the Json as a string and then use a Json parser to parse it to a JsonNode or whatever you want. And at last return a ResponseEntity. Below is a sample code. Do ask specific questions in the comment for clarification if needed.

@RequestMapping(value = "/toggleB", method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<java.lang.String> sendCommand(@RequestBody String ident) {

    // Do your stuff

    return new ResponseEntity<String>("Some response data/message",new HttpHeaders(), HttpStatus.OK);
}

Upvotes: 2

Related Questions