1

My code is something like:

@XmlRootElement
@XmlType(propOrder = {"id", "name", "content", "disclaimer", "buttons"})
public class Product {
private String id;

private String  name;

private String content;

private String disclaimer;

private List<ProductButton> buttons = new ArrayList<ProductButton>();}

Service code is:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/GetProduct")
public Response getProduct() {
    try {
        Product product = generateProductById(productId);

        return Response.ok().entity(product).build();
    }
    catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        return Response.serverError().build();
    }
}

However the output json string is not in order.

My expected order is same as my object, however the result is: "name", "id", "content"...

Anyone got idea how i can achieve that?

--------------------------------------Updated--------------------------------

@JsonPropertyOrder({"id", "name", "content", "disclaimer", "buttons"})
public class Product {
private String id;

private String  name;

private String content;

private String disclaimer;

private List<ProductButton> buttons = new ArrayList<ProductButton>();}
ttt
  • 3,934
  • 8
  • 46
  • 85
  • What Entity Provider is used to map a `Product` to JSON? It looks like you are using JAXB. Are you using Jackson, Jettison, ...? How? –  Jul 04 '13 at 08:43
  • Perhaps [this](http://stackoverflow.com/a/12008007/1907906) helps. –  Jul 04 '13 at 08:45
  • @Tichodroma It seems the same as what i did. – ttt Jul 05 '13 at 04:06

1 Answers1

0

Use the resteasy-jackson-provider and then annotate your class with the @JsonPropertyOrder annotation.

Here is the Maven dependency for the provider. If you are not using Maven just add this jar to your classpath.

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>${resteasy.version}</version>
    </dependency>

Example:

@JsonPropertyOrder({
    "user_id",
    "user_name",
    "email"
})
public class User
{
    @JsonProperty("user_id")
    private Long userId;

    @JsonProperty("user_name")
    private String username;

    private String email;

    //Getters and Setters Removed for Brevity
}
gregwhitaker
  • 13,124
  • 7
  • 69
  • 78
  • I did the same as your example, but still got the old output json. The order is not the same as I put in the JsonPropertyOrder annotation. – ttt Jul 08 '13 at 02:36
  • Can you please post your annotated bean? The above is the way to do it with Jackson. – gregwhitaker Jul 08 '13 at 02:54
  • Please see the code below updated, yes I switch jaxb to Jackson provider in the maven pom file. – ttt Jul 09 '13 at 01:50