学习笔记:从JSON数据中提取嵌套字符串与实体类对象
一、使用JsonNode
提取嵌套字符串
示例JSON
{
"unwantedData" : {
"someKey" : "someValue" ,
"anotherKey" : "anotherValue"
} ,
"targetInfo" : {
"nestedString" : "This is the string I want to extract"
}
}
目标:提取targetInfo.nestedString
处的字符串值。
Java代码示例
import com. fasterxml. jackson. databind. JsonNode ;
import com. fasterxml. jackson. databind. ObjectMapper ;
public class ExtractNestedStringExample {
public static void main ( String [ ] args) throws Exception {
String json = . . . ;
ObjectMapper objectMapper = new ObjectMapper ( ) ;
JsonNode rootNode = objectMapper. readTree ( json) ;
String nestedString = rootNode. get ( "targetInfo" ) . get ( "nestedString" ) . asText ( ) ;
String nestedString = rootNode. path ( "targetInfo" ) . path ( "nestedString" ) . asText ( ) ;
System . out. println ( "Extracted nested string: " + nestedString) ;
}
}
二、get()
与path()
方法的区别
get()
方法
直接访问JSON节点。 如果指定的键在当前节点中不存在,抛出MissingNodeException
异常。 优点:执行效率可能稍高。 缺点:遇到不存在的键时会立即抛出异常,可能导致程序中断。 path()
方法
访问JSON节点,遇到不存在的键时返回MissingNode
对象。 MissingNode
表示一个不存在的节点,对其操作(如asText()
)通常返回空值或默认值,而非抛出异常。优点:更稳健,即使遇到不存在的键也不会抛出异常,允许程序继续执行。 缺点:理论上执行效率可能略低于get()
方法,但实际应用中差异微乎其微。
三、提取顶层字符串
对于仅提取顶层字符串,无论使用get()
还是path()
方法,都可以直接对顶层键名进行操作,效果相同。 选择get()
还是path()
主要取决于对JSON数据完整性和异常处理的要求:
确保JSON结构符合预期,希望在遇到错误时立即终止程序:使用get()
方法。 处理可能含有缺失节点的JSON数据,希望程序在遇到缺失节点时仍能继续运行:使用path()
方法。
四、提取嵌套实体类对象
示例JSON
{
"unwantedData" : {
"someKey" : "someValue" ,
"anotherKey" : "anotherValue"
} ,
"targetEntity" : {
"id" : 1 ,
"name" : "John Doe" ,
"address" : {
"street" : "123 Main St" ,
"city" : "Anytown" ,
"country" : "USA"
}
}
}
目标:提取targetEntity
字段所对应的实体类对象(假设为User
类),并忽略顶层的其他数据。
Java代码示例
import com. fasterxml. jackson. databind. JsonNode ;
import com. fasterxml. jackson. databind. ObjectMapper ;
public class ExtractNestedEntityExample {
public static void main ( String [ ] args) throws Exception {
String json = . . . ;
ObjectMapper objectMapper = new ObjectMapper ( ) ;
JsonNode rootNode = objectMapper. readTree ( json) ;
String nestedEntityJson = objectMapper. writeValueAsString ( rootNode. get ( "targetEntity" ) ) ;
User user = objectMapper. readValue ( nestedEntityJson, User . class ) ;
System . out. println ( "User Details:" ) ;
System . out. println ( "ID: " + user. getId ( ) ) ;
System . out. println ( "Name: " + user. getName ( ) ) ;
System . out. println ( "\nAddress:" ) ;
Address address = user. getAddress ( ) ;
System . out. println ( "Street: " + address. getStreet ( ) ) ;
System . out. println ( "City: " + address. getCity ( ) ) ;
System . out. println ( "Country: " + address. getCountry ( ) ) ;
}
}
解释
使用ObjectMapper
将整个JSON解析为JsonNode
,然后通过get("targetEntity")
提取出嵌套的实体类数据对应的JSON节点。 将提取出的JSON节点使用writeValueAsString()
方法转换为JSON字符串,以便后续单独转换为实体类对象。 使用readValue()
方法将JSON字符串转换为所需的User
实体类对象。