gpt4 book ai didi

java - 使用 Jackson 获取数组的大小

转载 作者:行者123 更新时间:2023-12-02 03:08:53 25 4
gpt4 key购买 nike

我的 json 文件中有以下数据。

{  
"product":"Data",
"data":{
"zip":[
{
"codeValue":"12345",
"distance":[
{
"5":"a c"
},
{
"2":"z c"
}
]
},
{
"codeValue":"60089",
"distance":[
{
"5":"a c"
},
{
"2":"z c"
}
]
}
]
}
}

我正在尝试使用以下代码打印 zip 大小。

public void getJsonResponse() throws Exception {
String text = getTheData();
System.out.println(text);
ObjectMapper objMap = new ObjectMapper();
Map<String, Object> map = objMap.readValue(text, new TypeReference<Map<String, Object>>() {
});

String mainMap = map.get("product").toString();
String getData = map.get("data").toString();
Map<String, Object> map1 = objMap.readValue(getData, new TypeReference<Map<String, Object>>() {
});
List zip = (List) map1.get("zip");
System.out.println(zip.size());
}

此处而不是 zip.size() 上的 sysout,如果我使用 mainMap,我得到的输出为 Data,但是当我使用 zip.size() 时,我得到一些异常,如

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('z' (code 122)): was expecting double-quote to start field name at [Source: java.io.StringReader@60f82f98; line: 1, column: 3] at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524) at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557) at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:475) at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddName(ReaderBasedJsonParser.java:1293) at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._parseName(ReaderBasedJsonParser.java:1190) at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:612) at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:412) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:312) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2993) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2105) at onlyJava.JsonDataCAll.getJsonResponse(JsonDataCAll.java:24) at onlyJava.Test.main(Test.java:13)

请让我知道我哪里出了问题以及如何解决这个问题。

最佳答案

String getData = map.get("data").toString();

这不会向您返回 JSON,因此会出现异常。你会得到类似 {zip=[{...

相反,请更改您的声明

Map<String, Object> map1 = objMap.readValue(getData, new TypeReference<Map<String, Object>>() {
});

Map<String, Object> map1 = (Map<String, Object>) map.get("data");

关于java - 使用 Jackson 获取数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341679/

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