gpt4 book ai didi

java - 无法编写JSON:直接自引用导致循环

转载 作者:行者123 更新时间:2023-12-01 18:29:42 25 4
gpt4 key购买 nike

得到这个错误:


嵌套异常为
com.fasterxml.jackson.databind.JsonMappingException:直接
自参考导致循环(通过参考链:
com.google.gson.JsonObject [“ asJsonObject”])


尝试执行此操作时:

 restTemplate.postForObject(url_final, convertedObject, Object[].class);


其中 convertedObjectJSONObjecturlfinalString网址。

有效负载为:

"data" : [
{"FILENAME":"EEC1.TXT",
"ERRORDESCRIPTION":"FTD-07-INVALID CHARACTER FOUND IN THE FILE.",
"LINENO":3},
{"FILENAME":"SEC1.TXT",
"ERRORDESCRIPTION":"26-FTD-07-INVALID CHARACTER FOUND IN THE FILE.",
"LINENO":447}]


我的代码:

JSONObject output = new JSONObject(payload);
JSONArray jsonArray = output.getJSONArray("data");
JSONObject objects = jsonArray.getJSONObject(0);
String fileName = objects.getString("FILENAME");
int lineNumber = objects.getInt("LINENO");
String errordesc = objects.getString("ERRORDESCRIPTION");
String tempor = "{\"activityType\": \"trial.start\",\"aFileName\":\""
+ fileName
+ "\",\"aLINENO\": \""
+ lineNumber
+ "\",\"aREFNO\": \""
+ TxnNo
+ "\", \"aERRORDESCRIPTION\": \""+errordesc+"\"}";
JsonObject convertedObject = new Gson().fromJson(tempor, JsonObject.class);
restTemplate.postForObject(url_final, convertedObject, Object[].class);

最佳答案

在十行中,您混合了3个不同的JSON库:


JSONObject来自org.json
Gson来自Google的gson
restTemplate在后台使用Jackson


您应该跳过前两个并且仅使用Jackson。更改后的上述代码如下所示:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

....

ObjectMapper mapper = JsonMapper.builder().build();

JsonNode output = mapper.readTree(payload);

ArrayNode jsonArray = (ArrayNode)output.get("data");
JsonNode objects = jsonArray.get(0);
String fileName = objects.get("FILENAME").asText();
int lineNumber = objects.get("LINENO").asInt();
String errordesc = objects.get("ERRORDESCRIPTION").asText();
String tempor = "{\"activityType\": \"trial.start\",\"aFileName\":\""
+ fileName
+ "\",\"aLINENO\": \""
+ lineNumber
+ "\",\"aREFNO\": \""
+ TxnNo
+ "\", \"aERRORDESCRIPTION\": \""+errordesc+"\"}";
JsonNode convertedObject = mapper.readTree(tempor);


从版本 2.10.0开始,您可以使用 JsonMapper.builder().build(),但在以前的版本中,您只能通过 new ObjectMapper()创建新实例,这也很好。

关于java - 无法编写JSON:直接自引用导致循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com