Shri
Shri

Reputation: 121

Why I am not able to send list of strings as json response in Spring Rest?

I have built a simple spring rest application that has just one rest controller.

DemoRestController.java:


import java.util.Arrays;
import java.util.List;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class DemoRestController {
    
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello";
    }
    
    @GetMapping(value="/get-fruits", consumes=MediaType.ALL_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
    public List<String> getFruits() {
        List<String> fruits = Arrays.asList("Apple", "Banana", "Pear");
        return fruits;
    }
}

On running this app, I get:

org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver logException
WARNING: Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.util.Arrays$ArrayList] with preset Content-Type 'null']

I have added all the Jackson libraries for json serialization and deserialization in the WebContent\WEB-INF\lib. I am not using maven right now. I manually added the dependencies of Spring and Jackson for learning purpose.

Won't the types like array of built in types(eg array of strings) or list of built in types(list of strings) automatically convert into json format?

And what if we have custom type/entity that we want to send in response like list of Student, do we use ResponseEntity<T>? Please give me some example on this.

Upvotes: 0

Views: 153

Answers (1)

Dev Vaghasiya
Dev Vaghasiya

Reputation: 77

I am using like this for List<> response

@GetMapping("/YOUR_API_URL")  
public Response<Object> YOUR_METHOD_NAME(@RequestParam String id){
   List<RESPONSE_CLASS>response = YOUR_SERVICE.YOUR_SERVICE_METHOD(id);
     returnResponse.ok().setData(response).setMessage("YOUR_RESPONSE_MESSAGE"); 
}

This is my Response class:

@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response<T> {

    private Status status;
    private T data;
    private String message;
}

Your code is also work for me:

@GetMapping(value="/get-fruits",
    consumes=MediaType.ALL_VALUE,
    produces=MediaType.APPLICATION_JSON_VALUE)
public List<String> getFruits(){
  return Arrays.asList("Apple", "Banana", "Pear");
}

This is your code response:

[
  "Apple",
  "Banana",
  "Pear"
]

Upvotes: 0

Related Questions