我在向JSON
ArrayList
时遇到问题
我有课程计划
public class Plan {
private String planId;
private String planName;
:
:
}
和ArrayList
计划 - 计划清单
public class PlanList {
private List<Plan> plans = new ArrayList<Plan>();
:
:
}
我有以下POST和GET REST API
@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);
我使用Postman发布以下JSON,遵循GET返回的相同格式。
{
"plans": [
{
"planId":"1",
"planName":"Plan 1"
},
{
"planId":"2",
"planName":"Plan 2"
},
{
"planId":"3",
"planName":"Plan 3"
}
]
}
当我在createPlans()开头点击断点时,参数 plans 为空List
。
JSON格式不正确吗?我的REST定义是错误的吗?
答案 0 :(得分:0)
您可以使用org.json库中的JSONObject
和JSONArray
:
//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}]