我有一个 Spring 控制器方法,该方法将@RequestBody
指定为参数。请求正文的类如下所示
public class myClass {
CustomObject obj
int x
int y
int[] values
Character c
//getters and setters
}
我正在编写单元测试,并且在通过普通 JSON 对象设置int[] values
元素时遇到问题。如果可能的话,我宁愿不使用 JSONArray,因为其他元素通过 JSONObject 传递得很好,如下所示:
JSONObject requestParams = new JSONObject();
if(obj != null)
requestParams.put("obj", obj);
if(c != null)
requestParams.put("c", c);
我已经尝试了requestParams.put("values", Arrays.toString(values))
值定义为int[] values = new int[]{10,20,30,40,50,60,10,15,20,30,40,55}
但当我尝试发送请求时仍然收到 400 错误,只有当values
不为 null 时。
如何通过 JSONObject 将此值列表发送到 RequestBody 类?
你可以像下面这样使用:
//prepare list
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
...
list.add(100);
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("values", array);
}catch(JSONException ee){
}
以上是简化的方法,您可以减少样板代码。
不能解析数组到对象,尝试使用ObjectMapper
解析到ArrayNode
:
int[] values = new int[]{10,20,30,40,50,60,10,15,20,30,40,55};
ObjectMapper mapper = new ObjectMapper();
ArrayNode node = mapper.valueToTree(values);