akonsu
akonsu

Reputation: 29536

accept multiple JSON formats in web service

In my REST web service I need to accept JSON that can have two different structures.

Currently I have:

@Path("/")
public class MyAppResource {
    ...
    @Context private HttpServletRequest request;
    ...
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public MyResponseItem check(MyRequestItem body) {
        ...
    }
}

where

public class MyRequestItem {
    ...
    @JsonCreator
    public MyRequestItem(@JsonProperty("data") ArrayList<TextItem> data) {
        ...
    }
    ...
}

and

class TextItem {
    ...
    @JsonCreator
    public TextItem(@JsonProperty("count") int count,
                    @JsonProperty("text") String text) {
        ...
    }
    ...
}

So it accepts JSON of the form {"data":[{"count":123,"text":"abc"},...]}.

In addition to the above format I need to accept this format: {"data":["abc",...]}. That is, I think I need to change TextItem so that it can either be a String or a class as above.

How to achieve this?

Upvotes: 1

Views: 101

Answers (1)

varren
varren

Reputation: 14731

If you don't mind it to be the same class for both cases(TextItem), the easiest option for you is to add 1 more TextItem constructor with single string argument.

Here is demo:

public class Main {
    public static String json1 = "{\"data\":[{\"count\":123,\"text\":\"abc\"}]}";
    public static String json2 = "{\"data\":[\"abc\"]}";
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(json1, MyRequestItem.class));
        System.out.println(mapper.readValue(json2, MyRequestItem.class));
    }

    @Data //  lombok.Data;
    @ToString // lombok.ToString;
    public static class MyRequestItem {
        private List<TextItem> data;
        @JsonCreator
        public MyRequestItem(@JsonProperty("data") ArrayList<TextItem> data) {
            this.data = data;
        }
    }

    @Data
    @ToString
    public static class TextItem {
        private int count;
        private String text;
        @JsonCreator
        public TextItem(@JsonProperty("count") int count,
                        @JsonProperty("text") String text) {
            this.count = count;
            this.text = text;
        }

        // this is the only thing you need to add to make it work
        public TextItem( String text) {
            this.text = text;
        }
    }
}

Result:

MyRequestItem(data=[TextItem(count=123, text=abc)])

MyRequestItem(data=[TextItem(count=0, text=abc)])

Upvotes: 1

Related Questions