Search code examples
javajsonrestjerseymoxy

Jersey Json Array to List conversion


i want to convert a Json Array into an objects List. Json Array is something like this:

{
"servers": [
{
"id": "616fb98f-46ca-475e-917e-2563e5a8cd19",
"links": [
{
   "href": "http://openstack.example.com/v2/openstack/
    servers/616fb98f-46ca-475e-917e-2563e5a8cd19",
   "rel": "self"
},
{
    "href": "http://openstack.example.com/openstack/servers/
    616fb98f-46ca-475e-917e-2563e5a8cd19",
    "rel": "bookmark"
}
        ],
"name": "new-server-test"
}
]
}

The classes i used to map this Json Array is:

@XmlRootElement
public class GetServersResponse{

    private List<Server> servers;
}

public class Server {

   private String id;
   private List<Link> links;
   private String name;
   //getter and setter methods
}

public class Link {

   private String href;
   private String rel;
   //getter and setter methods
}

The client is:

public class Openstack
{
    private final  Client c;
    private String output;
    private GetServersResponse clientResponse;
    WebTarget webTarget;
    private String token;

    public Openstack()
    {
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, Config.CONNECT_TIMEOUT);
        clientConfig.property(ClientProperties.READ_TIMEOUT, Config.READ_TIMEOUT);
        c = ClientBuilder.newClient(clientConfig);
    }
    public GetServersResponse getServers(String tenant_id)throws IOException
    {
        webTarget = c.target("www.myexample.com");
        clientResponse = webTarget.request()
                                  .header("X-Auth-Token",token)
                                  .accept(MediaType.APPLICATION_JSON_TYPE)
                                  .get(GetServersResponse.class);
        return (clientResponse);
    }

The problem is that Json returned to the client is always empty. Anyone has an idea of where can be the error? Thanks for your help!


Solution

  • In order to use the moxy feature properly, you MUST implement getter/setter method for all Java classes you use to map the json packet. In your case, you must implement set and get method for "List servers" and all the other property of objects involved in the conversion processing. If you are using Netbeans, you can use "Encapsulate Fileds" function from your objects properties in order to create very fast getter and setter methods. Enjoy (: