Search code examples
javajsonrestjax-rsdropwizard

I need to modify my code to accept multiple list of json objects in my POST request. How do we implement this ? Any suggestion would help me


I need to accept multiple lists of JSON Objects in my post request. My code is throwing an error when trying I'm giving multiple JSON Obejcts. Need some help in resolving this issue. This issue came up when working with Java-Dropwizard Project.

Here is what my code looks like.

My Resource Class ::

@Path("/api")
public class TestResource {

@POST
@Path("/post")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public TestRes returnData(final TestRes outData) {
    return outData;
}

My getter and setter methods are here

public class JsonTransformer {

    private String Name;
    @SerializedName("Entry Date")
    private String entryDate;
    private String Description;

    @JsonProperty("Name")
    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }
    @JsonProperty("Entry Date")
    public String getEntryDate() {
        return EntryDate;
    }

    public void setEntryDate(String EntryDate) {
        this.EntryDate = EntryDate;
    }

    @JsonProperty("About")
    public String getAbout() {
        return About;
    }
    public void setAbout(String About) {
        this.About = About;
    }

Input JSON Objects in the body of POST method ::

[
{
    "Name" : "Test-1",
    "Entry Date" : "01-01-1-2020",
    "About" : "Tester-1"
},

{
    "Name" : "Test-2",
    "Entry Date" : "01-01-1-2020",
    "About" : "Tester-2"
},
{
    "Name" : "Test-2",
    "Entry Date" : "01-01-1-2020",
    "About" : "Tester-3"
}
]

Expected Output ::

[
{
    "Name" : "Test-1",
    "Entry Date" : "01-01-1-2020",
    "About" : "Tester-1"
},

{
    "Name" : "Test-2",
    "Entry Date" : "01-01-1-2020",
    "About" : "Tester-2"
},
{
    "Name" : "Test-2",
    "Entry Date" : "01-01-1-2020",
    "About" : "Tester-3"
}
]

Solution

  • Your code takes a single TestRes object, and you're trying to send it an array.

    Change the parameter to List<TestRes> and then the input and your code will match.