I have configured in an Spring 3 application a ContentNegotiatingViewResolver so when I invoke a controller with a URL which looks like **.json it returns a json object using jackson library.
If I call this method:
#RequestMapping("/myURL.json")
public List<MyClass> myMethod(){
List<MyClass> mylist = myService.getList();
return mylist;
}
In the JSON I receive I have:
{"myClassList":[
{ object 1 in json },
{ object 2 in json },
{ object 3 in json } ...
]
}
my questions are: ¿is there any way to configure the name myClassList which is used in the json? ¿is it possible in this way a json without this variable (something like the following one)?
[
{ object 1 in json },
{ object 2 in json },
{ object 3 in json } ...
]
Thanks.
You can return a org.springframework.web.servlet.ModelAndView object, instead of a List object directly. On the modelAndView object you can set the name of the key. Please refer to the following snippet:
#RequestMapping("/myURL.json")
public ModelAndView myMethod(){
ModelAndView modelAndView = new ModelAndView();
List<MyClass> mylist = myService.getList();
modelAndView.addObject("MyClassName", myList);
return modelAndView;
}
Related
I've tried to serialize my Map<String, Map<MetricName, ? extends Metric>> object using Gson but I'm getting JSON String response.And also I have the metrics value and name in that inner Map<MetricName, ? extends Metric> Here is my code looks like:
#GetMapping(path = "/showRawKafkaMetrics", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<String> getMetrics() throws IOException, ClassNotFoundException {
List<String> list = new ArrayList<>();
Gson gson = new Gson();
for (MessageListenerContainer container : kafkaListenerEndpointRegistry.getListenerContainers()){
list.add(gson.toJson(container.metrics()));
}
return list;
}
I'm getting JSON String response
Well, you are returning List<String>
If you want Spring to return JSON, then add a response mapping for application/json (which you did; produces = MediaType.APPLICATION_JSON_VALUE)
If you're expecting some response like
{
"foo": {
"metric": "bar"
}
}
Then you cannot return List<?> since that is an Object/Map.
You should ideally have a concrete Response model class for each returned type.
I know this is very basic, but I have a problem with deserializing json using jackson when the format is like this :
I created a class Person with id, name and place and tried to read the results from API call using jackson (using the #JsonProperty annotation), but when I debug the persons variable is null:
json body:
{ people:[
{
"id":"0",
"name":"Bob",
"place":"Colorado",
},
{
"id":"1",
"name":"John",
"place":"Chicago",
},
{
"id":"2",
"name":"Marry",
"place":"Miami",
}
]}
RequestEntity<Void> reqEntity = RequestEntity.get(new URI(url))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<List<Person>> persons = template.exchange(reqEntity, new ParameterizedTypeReference<List<Person>>() {});
You should wrap your List<Person> in another Response object, which has a people field, containing your list:
public class PeopleResponse {
private List<Person> people;
// getter and setter
}
Then you can change your ResponseEntity according to that:
ResponseEntity<PeopleResponse> response = template.exchange(reqEntity, new ParameterizedTypeReference<PeopleResponse>() {});
List<Person> people = response.getBody().getPeople();
I was wondering if there was a way in Spring Boot to pass the IDs of an object in an Array which Spring Boot will then get the object details for rather than the full object
This is an issue for me as to find the object, it appears Spring Boot wants the full object which will not work in my case
For example
{
"request": [
"e77d8168-4217-43c9-a6dd-fb54957d1302"
]
}
Rather than having to pass
{
"request": [
{
"uuid": "e77d8168-4217-43c9-a6dd-fb54957d1302",
"name": "Object 1"
}
]
}
Yes. The problem is probably with the class you are using to map your List<String>. It must match your json. Your controller should be like:
#RestController
public class IdsController {
#PostMapping("endpoint")
public void postIds(#RequestBody IdRequest idRequest){
idRequest.getRequest().forEach(System.out::println);
}
}
And the request object:
public class IdRequest {
private List<String> request;
public List<String> getRequest() {
return request;
}
}
I have a #PostMapping that allows the user to send a plain json map, like:
{
"firstname": "john",
"lastname": "doh"
}
Servlet:
#RestController
public class PersonController {
#PostMapping("/generic")
public void post(Map<String, String> params) {
}
}
This works fine. But now I want to accept also a list of objects on the same endpoint. But I cannot just add another method that takes a different parameter. Because spring the complains about ambiguous mapping:
#PostMapping("/generic")
public void post2(List<Map<String, String>> params) {
}
Question: how can I accept json data that can be both a Map and a List? I could lateron continue in the business code conditionally if the input is either map/list. But how can I accept them at all in a spring controller side by side?
#PostMapping
public void post(JsonNode json) {
if (json.isObject()) {
Map<String, String> map = mapper.convertValue(json, Map.class);
} else if (json.isArray()) {
List<Map<String, String>> list = mapper.convertValue(json, List.class);
}
}
I'm trying to create a POST servlet that should be called with JSON request. The following should work, but does not. What might be missing?
#RestController
public class MyServlet {
#PostMapping("/")
public String test(#RequestParam String name, #RequestParam String[] params) {
return "name was: " + name;
}
}
JSON POST:
{
"name": "test",
"params": [
"first", "snd"
]
}
Result: name is always null. Why?
"Response could not be created: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present"
In general I don't pass a request param in a POST method. Instead, I am using a DTO to pass it in the body like:
#RequestMapping(value = "/items", method = RequestMethod.POST)
public void addItem(#RequestBody ItemDTO itemDTO)
Then, you need to create the ItemDTO as a POJO with the necessary fields.
In addition to #stzoannos answer, if you do not want to create POJO for json object, you can use google GSON library to parse json into JsonObject class, which allow to work with parameters through same as get and set methods.
JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
return "name is: " + jsonObj.get("name").getAsString();