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

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

介绍

创建 POJO 类用来解析和获取一个 JSON 字符串中的值有时并不方便,特别针对那些非常长的,多层嵌套的 JSON。我们可以将 JSON 解析成树形结构更方便。

前提条件

前面我们已经解析过一个简单的 和 嵌套的 JSON Object 成 JsonNode,参考如下:

Fetch Value From JSON Object Using JsonNode – Jackson – Get() & Path() Methods

Fetch Value From Nested JSON Object Using JsonNode – Jackson – At() Method

因为我们用到 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>

JSON Array

JSON Example
在这里插入图片描述
树形结构表示 JSON Array
你可以用一个在线工具 来浏览上面的 JSON,呈现树型结构:

在这里插入图片描述
一个 JSON Array 可能是 JSON Objects 的集合 或 JSON arrays,如下:

[
  [
    {
    
    
      "firstName": "Amod",
      "lastName": "Mahajan",
      "age": 28,
      "isMarried": false,
      "salary": 23456.54
    },
    {
    
    
      "firstName": "Rahul",
      "lastName": "Arora",
      "age": 32,
      "isMarried": true,
      "salary": 33456.54
    }
  ],
  [
    {
    
    
      "firstName": "Amod",
      "lastName": "Mahajan",
      "age": 28,
      "isMarried": false,
      "salary": 23456.54
    },
    {
    
    
      "firstName": "Rahul",
      "lastName": "Arora",
      "age": 32,
      "isMarried": true,
      "salary": 33456.54
    }
  ]
]

Deserialize 反序列化 JSON Array

我们用到 Jackson API 的 ObjectMapper 类,该类提供的 “readTree()” 方法负责将 JSON 内容 deserialization 反序列化成树形形式的JsonNode 集合

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

我们只需用一个 index 来获取一个数组的元素,这也是基于数组的概念。

// Creating an instance of ObjectMapper class
ObjectMapper objectMapper = new ObjectMapper();
// Get tree representation of json
JsonNode jsonTree = objectMapper.readTree(jsonArray);
		
// Get first json object and storing 
JsonNode firstJsonObject = jsonTree.get(0);
// Get second json object and storing 
JsonNode secondJsonObject = jsonTree.get(1);

如果你不确定解析的 JSON 是一个 JSON Object 或 JSON tree,你可以用 instanceof,如下:

// To know if tree is a JSON object or JSON array
System.out.println("Is parsed JSOn tree a JSON Object?"+ Boolean.toString(jsonTree instanceof ObjectNode));
System.out.println("Is parsed JSOn tree a JSON Array?"+ Boolean.toString(jsonTree instanceof ArrayNode));

注意 JsonNode 类是 ObjectNode 和 ArrayNode的父类。

如果你确定 JSON 就是一个 Object 或 Array,就可以直接装箱 case 成该类型。

ArrayNode jsonTree = (ArrayNode) objectMapper.readTree(jsonArray);

代码:

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;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
 
public class ParseJsonArrayToReadValues {
    
    
	
	@Test
	public void parseJsonArrayToReadValues() throws JsonMappingException, JsonProcessingException
	{
    
    
		String jsonArray = "[\r\n" + 
				"  {\r\n" + 
				"    \"firstName\": \"Amod\",\r\n" + 
				"    \"lastName\": \"Mahajan\",\r\n" + 
				"    \"age\": 28,\r\n" + 
				"    \"isMarried\": false,\r\n" + 
				"    \"salary\": 23456.54\r\n" + 
				"  },\r\n" + 
				"  {\r\n" + 
				"    \"firstName\": \"Rahul\",\r\n" + 
				"    \"lastName\": \"Arora\",\r\n" + 
				"    \"age\": 32,\r\n" + 
				"    \"isMarried\": true,\r\n" + 
				"    \"salary\": 33456.54\r\n" + 
				"  }\r\n" + 
				"]";
		
		
		// Creating an instance of ObjectMapper class
		ObjectMapper objectMapper = new ObjectMapper();
		// Get tree representation of json
		JsonNode jsonTree = objectMapper.readTree(jsonArray);
		
		// To know if tree is a JSON object or JSON array
		System.out.println("Is parsed JSOn tree a JSON Object?"+ Boolean.toString(jsonTree instanceof ObjectNode));
		System.out.println("Is parsed JSOn tree a JSON Array?"+ Boolean.toString(jsonTree instanceof ArrayNode));
		
		// Get first json object and storing 
		JsonNode firstJsonObject = jsonTree.get(0);
		// Get second json object and storing 
		JsonNode secondJsonObject = jsonTree.get(1);
		
		// Get value of firstName as string
		String firstName = firstJsonObject.get("firstName").asText();
		String lastName = firstJsonObject.get("lastName").asText();
		// Get value of married as boolean
		int age = firstJsonObject.get("age").asInt();
		boolean married = firstJsonObject.get("isMarried").asBoolean();
		double salary = firstJsonObject.get("salary").asLong();
		
		System.out.println("FirstName is : "+firstName);
		System.out.println("LastName is  : "+lastName);
		System.out.println("Age is   : "+age);
		System.out.println("Maritial status is    : "+married);
		System.out.println("Salary is: "+salary);
		
		
		// Get value of firstName as string
		firstName = secondJsonObject.get("firstName").asText();
		lastName = secondJsonObject.get("lastName").asText();
		// Get value of married as boolean
		age = secondJsonObject.get("age").asInt();
		married = secondJsonObject.get("isMarried").asBoolean();
		salary = secondJsonObject.get("salary").asLong();
		
		System.out.println("FirstName is : "+firstName);
		System.out.println("LastName is  : "+lastName);
		System.out.println("Age is   : "+age);
		System.out.println("Maritial status is    : "+married);
		System.out.println("Salary is: "+salary);
				
	}
 
}

输出:

Is parsed JSOn tree a JSON Object?false
Is parsed JSOn tree a JSON Array?true
FirstName is : Amod
LastName is  : Mahajan
Age is   : 28
Maritial status is    : false
Salary is: 23456.0
FirstName is : Rahul
LastName is  : Arora
Age is   : 32
Maritial status is    : true
Salary is: 33456.0

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/120379531
今日推荐