POSTing `JSON` to an `ArrayList` results in an empty List

837 views Asked by At

I have a problem POSTing JSON to an ArrayList

I have a class Plan

 public class Plan {
    private String planId;
    private String planName;
        :
        :
}

and an ArrayList of Plan - PlanList

public class PlanList {
    private List<Plan> plans = new ArrayList<Plan>();
        :
        :
}

I have the following POST and GET REST APIs

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public PlanList createPlans(@CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, PlanList plans, @HeaderParam("Organization-Id") String organizationIdByService);

@GET
@Produces(MediaType.APPLICATION_JSON)
public PlanList retrieveAllPlans(@CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, @HeaderParam("Organization-Id") String organizationIdByService);

I POST the following JSON using Postman, following the same format that is returned by the GET.

{
  "plans": [
    {
      "planId":"1",
      "planName":"Plan 1"
    },
    {
      "planId":"2",
      "planName":"Plan 2"
    },
    {
      "planId":"3",
      "planName":"Plan 3"
    }
  ]
}

When I hit the breakpoint at the start of createPlans(), the argument plans is an empty List.
Is the JSON incorrectly formatted? Is my REST definition wrong?

1

There are 1 answers

2
forzagreen On

You can use JSONObject and JSONArray from org.json library :

//instantiate plan1 
JSONObject plan1 = new JSONObject();
plan1.put("planId", 1);
plan1.put("planName", "Plan 1");

//or by passing a String if you want:
JSONObject plan2 = new JSONObject("{\"planId\":2, \"planName\":\"Plan 2\"}");

//put plan1 and plan2 in your Json array
JSONArray plans = new JSONArray();
plans.put(plan1);
plans.put(plan2);

System.out.println(plan1);
//returns: {"planName":"Plan 1","planId":1}

System.out.println(plans);
//returns: [{"planName":"Plan 1","planId":1},{"planName":"Plan 2","planId":1}]