我有一个 Java 中的 Jetty WebSocket 服务器,它接受 JSON 格式的传入消息并执行简单的解析。这是通过使用 Jackson databind library 来完成的将传入消息转换为 JsonNode
对象。我正在尝试验证某些数据字段,但在 isTextual()
方面遇到了令人困惑的问题。我已将其归结为最低限度的测试,但仍然无法弄清楚。
这基本上就是我所拥有的:
// sample JSON: {...,"key":"de305d54","topic":"de305d54"}
// action is another JsonNode that contains the "topic" and "key" fields
final JsonNode actionKey = validateKey(action.get("key"));
final JsonNode actionTopic = validateTopic(action.get("topic"));
// both validation functions perform the same check
private JsonNode validateKey(JsonNode key) throws Exception {
if (!key.isTextual())
throw new Exception("invalid key");
return key;
}
private JsonNode validateTopic(JsonNode topic) throws Exception {
if (!topic.isTextual())
throw new Exception("invalid topic");
return topic;
}
问题是这个总是抛出java.lang.Exception:无效主题
。
最重要的是,这是打印 JSON 值的结果:
System.out.println("topic is: " + action.get("topic"));
System.out.println("key is: " + action.get("key"));
// topic is: "de305d54"
// key is: "de305d54"
还有一个奇怪的证据:根据 the JsonNode docs textValue()
调用将不会进行任何类型转换,如果值不是 String
它将返回 null
。但 textValue()
的结果会打印一个字符串。
System.out.println(action.get("topic").textValue());
// de305d54
最佳答案
来自 jackson 文档:
public boolean isBinary(): Method that can be used to check if this node represents binary data (Base64 encoded). Although this will be externally written as Json String value, isTextual() will return false if this method returns true.
您的数据看起来类似于 Base64 编码。我怀疑这可能就是 isTextual() 返回 false 的原因。
关于java - JsonNode isTextual() 莫名其妙地返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30314120/