views:

138

answers:

2

Hello,

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.

A: 

If i remember correctly you can set the root element name using JAXB annotations for the Jackson mapper:

@XMLRootElement("MyClassName")
public class MyClass{
  [...]
}

check here:

https://jaxb.dev.java.net/nonav/2.2/docs/api/javax/xml/bind/annotation/XmlRootElement.html

and here for a simple example with Jackson:

http://ondra.zizka.cz/stranky/programovani/java/jaxb/jaxb-json-jackson-howto.texy

smeg4brains
It doesn't seem to work for me, but thanks anyway.
Javi
+1  A: 

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;
}
Jeroen Rosenberg