Restlet call that returns String[] or List<String> returns null with Jackson

604 Views Asked by At

I'm using the restlet library and Jackson to send JSON data, and I cannot get the following to return a json object for a List, I get null out of it and no errors:

public class Info extends ServerResource {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        Server server = new Server(Protocol.HTTP,8080,Info.class);
        System.out.println("Starting: " + args[0]);
      server.start();
      System.out.println("Start returned: " + args[1]);
      ObjectMapper mapper = new ObjectMapper();
      List<String> user = new ArrayList<String>();
      user.add("SDFE");
      user.add("XXYY");
      Object o = "user";
      mapper.writeValue(new File("/tmp/user.json"), o);
    }

    /*@Get("json")
    public String isAwake()
    {
        System.out.println("Getting true");
        return "true";
    }*/

    @Get("json")
   //   public List los()
   //public String[] los()
   public String los()
    {   
        ArrayList l = new ArrayList<String>();
      String[] sl = new String[2];

      sl[0] = "FDSSE";
      sl[1] = "ODSEF";

        l.add("ESDF");
        l.add("JJKE");
          //return l;
      return sl.toString();
          // return sl[0];
    }

As you might be able to tell from the comments, I've done this a number of ways, with List, Object, and String[] being returned. I cast the List to Object for that part.

If I return a plain String, it gets encoded and sent. I cannot make the List send back a JSON array

1

There are 1 best solutions below

2
On

I had a similar issue. If I understood everything correctly, Jackson needs a class to serialize, and had trouble when handed a list. So I fixed this by creating a class for the list, basically wrapping it:

public class MyObject {
    //object details with setters and getters
}

and then a second class that contained a list of those:

public class MyObjectList {
    private List<MyObject> myObjectList;
    //and appropriate setter and getter
}

Then my URL call was:

@GET
public MyObjectList getMyObject() {
    //method defined 
}

Hope that helps! If there's a better way I'll be curious to see it myself!