Search code examples
javajsonjerseyjax-rshttpful

JSON JAX-RS in Java


I'm using Jersey for a RESTful web service in Java. I'm consuming them from a PHP client. I have it working fine with JSON as follows:

PHP: (using httpful phar)

 $uri="http://localhost:8080/YYYYY/rest/common/json";
    $r = \Httpful\Request::post($uri)
    ->body({"name":"MyName"})->send();
    return $r;

Java RESTful WS:

@POST
@Path(value="json")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_JSON)
public String jsonTest(final JaxData data)
{
    System.out.println(data.toString());
    return "this is the name: "+data.name;
}

Java binding class:

@XmlRootElement
public class JaxData {
    @XmlElement public String name; 
}

Now what I want to do is to send the following JSON structure:

{
"title":"MyTitle",
"names":[
    {
        "name":"nameOne"
    },
    {
        "name":"nameTwo"
    }
],
"city":"MyCity",
"country": "MyCountry"
    }

So as you can see I want to send objects inside objects apart from the primitive types of Java. How can I do this from the Java side? Thank you!


Solution

  • Define an object representing the data you want to send. You can make the object arbitrarily deep (each level in your JSON can be mapped to a sub object).

    Here's an example to get you started:

    public class MyBean implements Serializable {
        private String title;
        private List<JaxData> names;
        private String city;
        private String country;
    
        // Constructors, getters/setters
    }
    
    @POST
    @Path(value="json")
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.APPLICATION_JSON)
    public String jsonTest(final MyBean data) {
        return data.toString();
    }