Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom json in Spring

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.

like image 326
Javi Avatar asked Sep 25 '26 11:09

Javi


1 Answers

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;
}
like image 191
Jeroen Rosenberg Avatar answered Sep 28 '26 01:09

Jeroen Rosenberg