REST Assured 44 - Fetch Value From JSON Object Using JsonNode – Jackson – Get() & Path() Methods

REST Assured 系列汇总 之 REST Assured 44 - Fetch Value From JSON Object Using JsonNode – Jackson – Get() & Path() Methods

介绍

当需要解析长的,嵌套的 JSON,用创建 POJO 类的方式不太方便,我们需要用 tree 结构更佳。

前提条件

Required Java Library

因为我们用到 Jackson API, 所以确保导入 Jackson Databind 依赖包。

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>

Tree representation of JSON Object

JSON Object

{
    
    
  "firstName": "Amod",
  "lastName": "Mahajan",
  "married": false,
  "salary": 2000.54,
  "addressPin": 45324
}

树形结构:
你可以用一个在线工具 来浏览上面的 JSON,呈现树型结构:
在这里插入图片描述
Deserialize a JSON Object to Tree

我们需要用到 Jackson API 中的 ObjectMapper 类,该类提供的 “readTree()” 方法负责反序列化 deserialize JSON 内容成树形表现形式的一系列 JsonNode 实例。

我们通过 JsonNode 类的 get() 和 path() 方法来获取值,然后转换成适合的数据类型。

import org.junit.Test;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class ParseJsonObjectToReadValues {
    
    
	
	@Test
	public void parseJsonObjectToReadValues() throws JsonMappingException, JsonProcessingException
	{
    
    
		String jsonObject = "{\r\n" + 
				"  \"firstName\": \"Amod\",\r\n" + 
				"  \"lastName\": \"Mahajan\",\r\n" + 
				"  \"married\": false,\r\n" + 
				"  \"salary\": 2000.54,\r\n" + 
				"  \"addressPin\": 45324\r\n" + 
				"}";
		// Creating an instance of ObjectMapper class
		ObjectMapper objectMapper = new ObjectMapper();
		// Get tree representation of json
		JsonNode jsonTree = objectMapper.readTree(jsonObject);
		// Get value of firstName as string
		String firstName = jsonTree.get("firstName").asText();
		String lastName = jsonTree.get("lastName").asText();
		// Get value of married as boolean
		boolean married = jsonTree.get("married").asBoolean();
		double salary = jsonTree.get("salary").asDouble();
		long addressPin = jsonTree.get("addressPin").asLong();
		
		System.out.println("FirstName is : "+firstName);
		System.out.println("LastName is  : "+lastName);
		System.out.println("Married is   : "+married);
		System.out.println("Salary is    : "+salary);
		System.out.println("Addresspin is: "+addressPin);
		
	}
 
}

输出:

FirstName is : Amod
LastName is  : Mahajan
Married is   : false
Salary is    : 2000.54
Addresspin is: 45324

观察上面的使用的方法 asText(), asBoolean() 就是为了解析成合适的值。如果不确实值的准确数据类型,可以通过类似 isTextual(), isBoolean() 方法帮助。

System.out.println(jsonTree.get("firstName").isTextual());
System.out.println(jsonTree.get("lastName").isTextual());
System.out.println(jsonTree.get("married").isBoolean());
System.out.println(jsonTree.get("salary").isDouble());
System.out.println(jsonTree.get("addressPin").isLong());

如果将值解析成错误的数据类型,将不会抛出一个异常。例如:使用 asBoolean() 方法将一个 String 解析成一个 boolean,根据官方 Jackson API Java 文档,会有如下情况:

asBoolean() 方法将这个node的值转换成 boolean,JSON booleans 的映射关系是,integer 非零对应 true,0 对应 false; String ‘true’ 和 ‘false’ 分别对应布尔的 true 和 false。如果对象不能转换成一个 boolean 值 (包括 Arrays 和 Objects),默认会返回一个 false,不会抛异常。

asLong() 也类似, 该方法将 node 值转换成一个 Java long类型。数字采用强制转换规则, booleans 值 false 转换成 0, true 为 1. String 类型按默认的 Java 语言整数规则解析。如果对象不能转换成一个 loing 值 (包括 Arrays 和 Objects),默认会返回一个 0,不会抛异常。

Retrieving value for a non-existing node

当用 get() 方法获取一个不存在的 node 的值时,将会得到 NullPointerException 异常。

// Retrieving value of non-existing key
System.out.println(jsonTree.get("nonExistingNode").asText());

可以用这些重写方法 asText(String defaultValue), asInt(int defaultValue) 来处理不期望的 null 值。但是使用这些方法必须使用 get() 方法的替代方法 path() 方法。因为上面用 get() 将会得到 NullPointerException 异常。

根据官方文档 path() 方法类似 get(String) 方法,除了如果 node 不存在时不会返回 null (由于这个node不是一个 object,或则是没有具体字段的 Object), 一个 “missing node” 将会返回,所以通过 path() 方法更安全。

// Retrieving value of non-existing key
		String s = jsonTree.get("nonExistingNode").asText();
		System.out.println(s);

上面代码将输出一个 NullPointerException 异常。

// Retrieving value of non-existing key using path
		String s1 = jsonTree.path("nonExistingNode").asText();
		System.out.println(s1);

上面代码将输出 “” 空字符串

Guess you like

Origin blog.csdn.net/wumingxiaoyao/article/details/120371023