如何在Java中解析具有空值的JSON对象?

问题描述 投票:0回答:1

我正在构建一个测试套件来测试我的Vert.x API,它实现了几种排序算法。我想介绍的一个测试用例是处理未排序数组中的null或空值:

请求正文是我创建的JSON字符串,如下所示:

final String json = "{\"arr\": [99, [2, 4, ], [[55]], 0]}";

目前我正在使用Vert.x JsonObject和JsonArray在请求处理程序中解析JSON。

import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;

private void doBubbleSort(RoutingContext routingContext) {

    JsonObject json = routingContext.getBodyAsJson();
    JsonArray jsonArray = json.getJsonArray("arr");

    ....

}

这是我得到的错误

    SEVERE: Unexpected exception in route
    io.vertx.core.json.DecodeException: Failed to decode:Unexpected character (',' (code 44)): expected a value
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 49]
    at io.vertx.core.json.Json.decodeValue(Json.java:172)
    at io.vertx.core.json.JsonObject.fromBuffer(JsonObject.java:960)
    at io.vertx.core.json.JsonObject.<init>(JsonObject.java:73)
    at io.vertx.ext.web.impl.RoutingContextImpl.getBodyAsJson(RoutingContextImpl.java:263)
    at io.vertx.ext.web.impl.RoutingContextDecorator.getBodyAsJson(RoutingContextDecorator.java:123)
    at za.co.offerzen.SortVerticle.doBubbleSort(SortVerticle.java:80)
    at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:272)
    at io.vertx.core.impl.TaskQueue.run(TaskQueue.java:76)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:748)

如果json中有空值,我该如何解析请求?理想情况下,我只想要请求体中的所有int值,并忽略或去掉空值,空值或缺失值。在将其解析为json之前,是否需要迭代请求体,并检查每个值是否为instanceof int?或者还有另一种方式吗?

除了JsonObjectJsonArray,我可以获得请求正文作为BufferString

谢谢。

json java-8 null vert.x
1个回答
0
投票

如果你的意思是:

理想情况下,我只想要请求体中的所有int值

你可以简单地做到以下几点:

    final String json = "{\"arr\": [99, [2, 4, ], [[55]], 0]}";
    final String regularExpression = "([^\\d])+";
    Pattern pattern = Pattern.compile(regularExpression);
    String[] results = pattern.split(json);
    List<Integer> numbers = new ArrayList<>();
    for (String result : results) {
        try {
            numbers.add(Integer.valueOf(result));
        } catch (NumberFormatException e) {

        }

    }
    for (int number : numbers) {
        System.out.println(number);
    }

这将输出:

99
2
4
55
0

但这真的不会让人觉得这是一个json。它只是从字符串中提取数字。

© www.soinside.com 2019 - 2024. All rights reserved.