使用中为了统一返回的数据格式,需要我们处理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",
}