使用中爲了統一返回的數據格式,需要我們處理json數據後,返回同樣的結果數據然後解析,測試案例如下:
package flinkonkafka;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class RequestJson {
public static void main(String[] args) throws JsonProcessingException {
String s = "{\"result\": {\"data\": [{\"code\": \"CF327\",\"value\": \"0.0016592020664306757\"},{\"code\": \"CF327\",\"value\": \"0.0016592020664306757\"}],\"message\": \"計算成功!\",\"status\": 0}}";
JSONObject jsonobj = JSON.parseObject(s);
JSONObject paramzObject = jsonobj.getJSONObject("result");
JSONArray feedsArray = paramzObject.getJSONArray("data");
//這裏可以將我們的json字符串直接轉成我們需要的對象
for (int i = 0; i < feedsArray.size(); i++) {
JSONObject sonObject = feedsArray.getJSONObject(i);
ObjectMapper mapper = new ObjectMapper();
CalResultVo result = mapper.readValue(sonObject.toString(), CalResultVo.class);
System.out.println(result.getCode());
}
}
//獲取回調標籤計算的參數map
public static Map<String, Object> getParameterJsonMap(String json) {
//將json字符串轉換成jsonObject對象
JSONObject jsonobj = JSON.parseObject(json);
JSONObject jsonParm = jsonobj.getJSONObject("parameter");
Map<String, Object> parameterMap = (Map) JSON.parse(jsonParm.toString());
return parameterMap;
}
public String getCallbackUrl(String json) {
JSONObject jsonobj = JSON.parseObject(json);
String callbackUrl = jsonobj.getString("callbackUrl");
return callbackUrl;
}
//返回封裝的 json結果數據
public static String callBackJson(String json, Long handleTs, String data, String message) {//List<CalResultVo>
JSONObject jsonobj = JSON.parseObject(json);
JSONObject jsonResult = jsonobj.getJSONObject("result");
Map<String, Object> result = (Map) JSON.parse(jsonResult.toString());
result.put("data", data); //返回計算結果
result.put("message", message);//返回響應信息
jsonobj.put("result", result);
jsonobj.put("handleTs", handleTs); //處理結束時間
return jsonobj.toString();
}
}
最後的結果json如下:
{
"result": {
"data": [{
"code": "T001",
"value": "0.0735855686"
}],
"message": "計算成功!",
"status": 0
},
"requestType": "SYNC",
"idxCode": "001",
"requestId": "0.01",
"parameter": {
"flinkPort": 8081,
"port": "2181",
"hengheUser": "sa"
},
"handleTs": 1593674776820,
"topic": "topic-test",
"createTs": "1593674770",
}