首页 > 解决方案 > 在 GSON 中期望字符串时如何处理布尔值?

问题描述

我目前正在使用第 3 方 REST API 进行开发。我正在为 API 返回的 JSON 对象创建对象。我正在关注他们的文档,其中说某些变量将是字符串。有时当没有 String 时,它会返回 False。有时我期待一个 URL,但我得到了 False。

我该如何处理?

这是有问题的 API https://developers.cannabisreports.com/docs/

应变对象示例:https ://ghostbin.com/paste/kgeau 在应变对象中,执行搜索时出现异常。一些搜索结果在被注释掉的代码位中有布尔值而不是字符串/url。

有时我得到这个

"genetics": {
            "names": false,
            "ucpc": false,
            "link": false
        }

有时我能得到这个

"genetics": {
            "names": "Blueberry x Haze",
            "ucpc": "W74AFGH22Z000000000000000 x 9XVU7WJQCD000000000000000",
            "link": "https:\/\/www.cannabisreports.com\/api\/v1.0\/strains\/9XVU7PTG2P000000000000000\/genetics"
        }

标签: javajsonrestapigson

解决方案


当您遇到设计不佳的 API 时,Gson 为您提供了一些灵活性,同时反序列化由此类 API 生成的 JSON 文档。尽管您有多种解决此问题的方法(例如JsonDeserializer等),但您大多喜欢面临我似乎已经在这里看到的false-as-null问题。您可以通过标记“错误”字段来帮助 Gson:

final class Envelope {

    final Genetics genetics = null;

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("genetics", genetics)
                .toString();
    }

}
final class Genetics {

    @JsonAdapter(FalseAsNullTypeAdapterFactory.class)
    final String names = null;

    @JsonAdapter(FalseAsNullTypeAdapterFactory.class)
    final String ucpc = null;

    @JsonAdapter(FalseAsNullTypeAdapterFactory.class)
    final URL link = null;

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("names", names)
                .add("ucpc", ucpc)
                .add("link", link)
                .toString();
    }

}

这就是类型适配器工厂的实现方式:

final class FalseAsNullTypeAdapterFactory
        implements TypeAdapterFactory {

    // No worries, Gson will instantiate it itself
    private FalseAsNullTypeAdapterFactory() {
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
        final TypeAdapter<T> delegateAdapter = gson.getAdapter(typeToken);
        return new TypeAdapter<T>() {
            @Override
            public void write(final JsonWriter out, final T value)
                    throws IOException {
                delegateAdapter.write(out, value);
            }

            @Override
            public T read(final JsonReader in)
                    throws IOException {
                // If the next token is a boolean
                if ( in.peek() == JsonToken.BOOLEAN ) {
                    // and it's true
                    if ( in.nextBoolean() ) {
                        // then just report an unexpected `true` literal
                        throw new MalformedJsonException("Expected a null value indicator as `false`. " + in);
                    }
                    // and it's false, then we assume it's a null
                    return null;
                }
                // Otherwise read the whole value as a usual
                return delegateAdapter.read(in);
            }
        };
    }

}

反序列化问题中提供的 JSON 文档后,toString-ed 映射可能会产生如下内容:

Envelope{genetics=Genetics{names=null, ucpc=null, link=null}}  
Envelope{genetics=Genetics{names=Blueberry x Haze, ucpc=W74AFGH22Z000000000000000 x 9XVU7WJQCD000000000000000, link=https://www.cannabisreports.com/api/v1.0/strains/9XVU7PTG2P000000000000000/genetics}}  

推荐阅读