杰克逊读取价值为字符串

Edi*_*son 29 java json jackson

比方说,我有一个价值未知的物体

{
 "data": [
    {"a":...,
    "dont_know_what_else_is_here":....}
 ]
}
Run Code Online (Sandbox Code Playgroud)

我只想将"data"的值作为字符串存储到变量/数据库中.

我应该如何从流API中读取它?

And*_*nov 41

如果您已经读过这个对象JsonNode,可以这样做:

String content = jsonNode.get("data").textValue();
Run Code Online (Sandbox Code Playgroud)

UPD:既然您正在使用流式解析器,那么这个关于Jackson使用的示例可能有所帮助.

UPD:方法名称现在是textValue() - docs

  • @joeybaruch asText()会将任何非文本转换为字符串值,而textValue()则将其转换为字符串. (4认同)

小智 18

当我们尝试从JsonNode获取字符串形式的数据时,我们通常使用asText,但我们应该使用textValue.

asText:如果节点是值节点(方法isValueNode()返回true),则返回容器值的有效String表示的方法,否则为空String.

textValue:用于访问String值的方法.不对非String值节点进行任何转换; 对于非String值(其中isTextual()返回false)将返回null.对于String值,永远不会返回null(但可能是空字符串)

让我们举一个例子,

JsonNode getJsonData(){
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = mapper.createObjectNode(); 
    node.put("anyParameter",null);
    return node;
}
JsonNode node = getJsonData();
json.get("anyParameter").asText() // this will give output as "null"
json.get("").textValue() // this will give output as null
Run Code Online (Sandbox Code Playgroud)


dej*_*avu 6

您可以根据键值对在地图中获取数据.

Map<String, Object> mp = mapper.readValue(new File("xyz.txt"),new TypeReference<Map<String, Object>>() {});
Run Code Online (Sandbox Code Playgroud)

现在从map获取值:

mp.get("data");
Run Code Online (Sandbox Code Playgroud)


Dmi*_*try 5

假设您已经有了一个解析器并且它指向“数据”标记(例如来自自定义反序列化器),您可以执行以下操作:

ObjectMapper mapper = new ObjectMapper();
JsonNode treeNode = mapper.readTree(parser);
return treeNode.toString();
Run Code Online (Sandbox Code Playgroud)

这将为您提供包含“data”值的字符串。