/java/

Jersey Client. Json to Object

2013-08-15 17:45:58

Json to Post Json to List

public class PostClient {

    public void getOnePost() {

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource service = client.resource(getBaseURI());

        Post post = service.path("api").path("post").path("1").accept(MediaType.APPLICATION_XML).get(Post.class);

        System.out.println(post);
    }

    public void getPosts() {

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource service = client.resource(getBaseURI());

        List<post> posts = service.path("api").path("post").accept(MediaType.APPLICATION_XML).get(new GenericType<list<post>&gt;(){});

        System.out.println(posts);
    }

    private static URI getBaseURI() {
        return UriBuilder.fromUri("http://localhost:8080/Jersey/").build();
    }
}
@Path("/post")
public class PostApi {

  @GET
  @Path("/1")
  @Produces({ MediaType.APPLICATION_XML })
  public Post getPostJson() {
    return new Post(1,"lorem","ipsum");
  }

  @GET
  @Path("/")
  @Produces({ MediaType.APPLICATION_XML })
  public List<post> getPostsJeson(){
      List<post> posts = new ArrayList<post>();
      posts.add(new Post(1, "title 1", "desc 1"));
      posts.add(new Post(2, "title 2", "desc 2"));
      posts.add(new Post(3, "title 3", "desc 3"));
      return posts;
  }
}