return json array from spring controller

11,825

Solution 1

You should return a java List, not a JSONArray. Spring uses Jackson, and the purpose of jackson is to convert java object to/from base elements like JsonArray, and then to a Json String

You don't need to directly manage json, Spring does it all for you, so the solution here is to change your return types (of the controller and the service) and manage only java Objects

@RequestMapping(value = "/generate", method = RequestMethod.GET) 
@ResponseBody public List<YourFacturerClass> generate() {

    return facturationSvc.facturer();

}

Solution 2

you should be returning string not JSONArray,

String generate() throws NoSuchFieldException, CloneNotSupportedException{

      return facturationSvc.facturer().toString();
}
Share:
11,825
R.Walid
Author by

R.Walid

Updated on June 14, 2022

Comments

  • R.Walid
    R.Walid almost 2 years

    I want to return with my controller spring a JSONARRAY, but when running I receive this error:

    java.lang.IllegalArgumentException: No converter found for return value of type: class org.codehaus.jettison.json.JSONArray

    this is my code :

    @RequestMapping(value = "/generate", method = RequestMethod.GET)
    @ResponseBody
    public JSONArray generate() throws NoSuchFieldException, CloneNotSupportedException{
    
            return facturationSvc.facturer();
    }
    

    NB:The method "facturer()" of the service "facturationSvc" , returns a JSON ARRAY

  • pdem
    pdem about 7 years
    It works, but in Spring we dont need to use directly JsonArray
  • R.Walid
    R.Walid about 7 years
    Yes, that's what I did. Thank you