gpt4 book ai didi

java - 无法写入 JSON : Direct self-reference leading to cycle

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

收到此错误:

nested exception is com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference leading to cycle (through reference chain: com.google.gson.JsonObject["asJsonObject"])

当尝试这样做时:

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

其中 convertedObjectJSONObjecturlfinalString url。

有效负载是:

"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 : Direct self-reference leading to cycle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781527/

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