本文介绍了Jackson Json Mapper:没有场地或空地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Jackson Json Mapper来解析我服务器上的查询。

I use Jackson Json Mapper to parse queries on my server.

例如,我正在等待符合类 My_class :

For example, I'm waiting for query which fits class My_class:

class My_class {
     String a;
     String b;
}

我以这种方式反序列化查询:

I deserialize queries this way:

public <T> T Deserialize(String json, Class<T> type) throws DeserializationException {
        if (json == null || type == null) {
            throw new IllegalArgumentException();
        }
        try {
            return objectMapper.readValue(json, type);
        } catch (JsonParseException e) {
            throw new DeserializationException(e);
        } catch (org.codehaus.jackson.map.JsonMappingException e) {
            throw new DeserializationException(e);
        } catch (IOException e) {
            throw new DeserializationException(e);
        }
    }

以下是两个示例查询:

{"a":"test"}
{"a":"test", "b":null}

问题是我想知道用户何时向我发送仅包含字段的查询一个,当他发送一个字段 b 的查询设置为 null 。映射器在两种情况下都将字段 b 标记为 null

The problem is I want to know when a user sent me a query with only the field a and when he sent a query with field b set to null. The mapper marks field b as null in both situations.

有什么更好的方法(并避免编写自己的反序列化器)?

What is the better way to do this (and to avoid writing my own deserializer)?

推荐答案

你可以使用这个方法检查是 null literal。

You can use the method isNull() to check if the JsonNode is a null literal.

可用于检查此节点是否是从JSON文字空值创建的方法。

Method that can be used to check if this node was created from JSON literal null value.

也是,似乎有类似的用途。如果节点实际上不存在于JSON文档中,则它应该返回true。这种方法很有用,例如如果你想对未明确设置的属性使用默认值。

There is also isMissingNode(), which seems to have a similar purpose. It should return true if the node isn't actually present in the JSON document. This method is useful e.g. if you want to use default values for properties that aren't set explicitly.

对于虚拟节点返回true的方法,当没有实际节点匹配给定条件时,这些节点表示由路径访问器方法构造的缺失条目。

Method that returns true for "virtual" nodes which represent missing entries constructed by path accessor methods when there is no actual node matching given criteria.






在我看来,你应该避免构建取决于<$之间差异的东西c $ c> null 缺少节点。您实际上是在反序列化的JSON中添加了某种额外的数据类型:而不仅仅是 null 在这两种情况下都会返回大多数JSON API,现在您已经 null literal 缺少节点这不是常见做法。这很令人困惑,它可能会导致您的API出现问题,因为客户端需要做额外的工作来配置其序列化程序以区分这两种状态。可能并非所有JSON库都支持它。


In my opinion you should avoid building something that depends on the difference between null and missing nodes though. You are essentially adding some kind of additional data type to the deserialized JSON: instead of just null most JSON APIs return in both cases, you now have null literal and missing node which is not a common practice. It is confusing and it may cause issues with your API because the client needs to do extra work to configure its serializer to distinguish those two states too. It's possible that not all JSON libraries support that.

这篇关于Jackson Json Mapper:没有场地或空地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:55