在GSON中期待String时如何处理布尔值?

时间:2018-04-30 08:51:26

标签: java json rest api gson

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

我该如何处理?

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

应变对象示例:https://ghostbin.com/paste/kgeau 在Strain对象中,我在执行搜索时遇到异常。搜索的一些结果在注释掉的代码中有布尔值而不是字符串/ 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"
        }

2 个答案:

答案 0 :(得分:1)

当您遇到设计非常好的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}}  

答案 1 :(得分:0)

由于您已经知道自己将拥有booleanString,因此您可以直接获得JsonPrimitive

  

原始值可以是String,Java原语或Java原始包装类型。

然后从JsonPrimitive实例,您可以检查它是否isBoolean

以下是如何在小代码段中使用它

public static String getURL(JsonObject json, String value){
    JsonPrimitive data = json.get(value).getAsJsonPrimitive();
    if(data.isBoolean()){
        return "Boolean : " + data.getAsBoolean();
    } else {
        return "String : " + data.getAsString();
    }
}

以下是验证此逻辑的快速示例

public static void main(String[] args) {
    String data = 
            "{"
            + "    \"element\" : {"
            + "        \"a\":false,"
            + "        \"b\":\"foobar\""
            + "    }"
            + "}";
    JsonObject json = new JsonParser().parse(data).getAsJsonObject();
    JsonObject element = json.get("element").getAsJsonObject();
    System.out.println(getURL(element, "a"));
    System.out.println(getURL(element, "b"));
}
  

布尔值:false
  字符串:foobar

json使用了:

{
    "element" :{
        "a":false,
        "b":"foobar"
    }
}