问题描述
我正在使用Spring Boot创建REST API,并使用org.json解析从另一项不同服务检索的数据。从此服务中,我将获得以下格式的JSON数据
{
"my_data":[
{
"user_data":{
"first_name":"FirstTest1","last_name":"LastTest1","age":"25"
}
},{
"user_data":{
"first_name":"FirstTest2","last_name":"LastTest2","age":"35"
}
},{
"user_data":{
"first_name":"FirstTest3","last_name":"LastTest3","age":"45"
}
}
],"count":10,"is_safe":false
}
并且我必须将接收到的数据转换为以下JSON
[
{
"user_data":{
"first_name":"FirstTest1","age":"45"
}
}
]
我知道我可以使用POJO映射数据并将其发送(已经这样做),但是这里的问题是从另一个服务接收的数据是不固定的,例如它可能具有或可能具有“ first_name”或可能具有不同的字段,例如“ country”。因此,在这种情况下,我无法预先创建POJO。
浏览了一些在线资源之后,我进行了一些更改,并且POST Controller方法看起来像这样。
@PostMapping(path = "/searchusersdata")
public RETURN_SOMETHING searchUsersData(@RequestBody Map<String,String> searchData) {
List<JSONObject> finalDataCollection = new ArrayList<JSONObject>();
//Making some REST API CALL TO GET 'response' using 'searchData'
String someResponse = response.getBody();
JSONObject object = null;
try {
object = new JSONObject(someResponse);
} catch (JSONException e) {
e.printstacktrace();
}
String my_data= object.get("my_data").toString();
JSONArray intermediateJA = null;
intermediateJA = new JSONArray (my_data);
for(int i = 0; i < intermediateJA.length(); i++) {
JSONObject item = intermediateJA.getJSONObject(i);
if (item.keySet().contains("user_data"))
{
Object value = item.get("user_data");
finalDataCollection.add(new JSONObject(value));
}
}
//WHAT TO RESTURN HERE
}
现在,我不知道该怎么回报野兔。对于单个JSONObject,我们可以使用return new ResponseEntity<>(return_data.toMap(),HttpStatus.OK);
,但对于集合我不知道。如果需要以完全不同的方式进行操作,我愿意提出建议。我也知道使用gson或jackson可能会更容易,但是我必须使用org.json。
解决方法
代替List,使用JsonArray并使用ResponseEntity返回它。
示例
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonArray.put(jsonObject);
return new ResponseEntity( jsonArray.toString(),HttpStatus.OK);