【问题标题】:How to parse json value without keys using RestTemplate?如何使用 RestTemplate 解析没有键的 json 值?
【发布时间】:2019-11-23 08:42:43
【问题描述】:

我想解析 json 值,但是有些值没有键。

喜欢这个

"geometry": {
                "type": "LineString",
                "coordinates": [
                    [
                        127.08373748622218,
                        37.529508099979225
                    ],
                    [
                        127.08355138558433,
                        37.529735847943925
                    ]
                ]
            }

几何.class

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString
public class Geometry {
    private String type;
    private Coordinate coordinates;
}

坐标类

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString
public class Coordinate {
    private List<Double[]> xy;
}

然后我看到了这个错误

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `kr.seoulmaas.ieye.service.dto.path.walk.Coordinate` out of START_ARRAY token
 at [Source: (PushbackInputStream); line: 1, column: 133] (through reference chain: kr.seoulmaas.ieye.service.dto.path.WalkPathResDto["features"]->java.util.ArrayList[0]->kr.seoulmaas.ieye.service.dto.path.walk.Feature["geometry"]->kr.seoulmaas.ieye.service.dto.path.walk.Geometry["coordinates"])

【问题讨论】:

  • 发布一个 complete 最小示例,使用硬编码的 JSON 输入,尝试反序列化此 JSON 输入。
  • 显示RestTemplate代码

标签: java json spring-boot resttemplate


【解决方案1】:

private Coordinate coordinates; 应该是 private List&lt;Coordinate&gt; coordinates;,因为它是 JSON 中的一个数组,但由于该数组只包含数组,因此您需要一个列表列表:List&lt;List&lt;Double&gt;&gt; coordinates(由 @JBNizet 建议)。

【讨论】:

  • 它实际上应该是一个List>,或者直接是一个List。它不是一个对象,但也不是一个对象数组。
【解决方案2】:

在您的数据中,coordinateslistlist。所以用这种方式定义你的 Geometry 类:

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString
public class Geometry {
    private String type;
    private List<Coordinate> coordinates;
}

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    对不起,我来晚了。

    我使用 JsonNode 解决了这个问题。

    这是我的代码。

    public class Geometry {
        private String type;
        private JsonNode coordinates;
    }
    

    【讨论】:

    • 但是如何使用JsonArray解决了这个问题?有些人可能不清楚你是如何做到的。请更新您的答案并提供更多详细信息,谢谢!
    • 哦,对不起,我与 JsonNode 混淆了。我用 JsonNode 解决了这个问题。
    猜你喜欢
    • 2016-09-02
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2018-12-20
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多