Jackson library

In the Jackson library, the JsonNode class represents a node in a JSON tree. To extract a list (e.g., an array) from a JsonNode, you can use methods like get, elements(), or findValues. Here's how you can achieve this:

Example: Extracting a List from JsonNode

Given JSON:

{
  "names": ["Alice", "Bob", "Charlie"]
}

Java Code:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JsonNodeExample {
    public static void main(String[] args) throws Exception {
        String jsonString = "{ \"names\": [\"Alice\", \"Bob\", \"Charlie\"] }";

        // Parse JSON
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(jsonString);

        // Extract the "names" array as a JsonNode
        JsonNode namesNode = rootNode.get("names");

        // Convert JsonNode array to a List
        List<String> names = new ArrayList<>();
        if (namesNode.isArray()) {
            for (JsonNode nameNode : namesNode) {
                names.add(nameNode.asText());
            }
        }

        // Print the list
        System.out.println(names); // Output: [Alice, Bob, Charlie]
    }
}

Explanation

  1. Parse JSON: Use ObjectMapper.readTree to parse the JSON string into a JsonNode object.
  2. Access Array Node: Use rootNode.get("names") to get the JsonNode representing the array.
  3. Iterate and Convert: Check if the node is an array using isArray(). Iterate over its elements and convert each to the desired type (String in this case) using methods like asText().

Notes

  • Use asText(), asInt(), or asDouble() for type conversion.
  • Always check if the node is of the expected type (isArray, isTextual, etc.) to avoid runtime issues.

댓글

이 블로그의 인기 게시물

PYTHONPATH, Python 모듈 환경설정

You can use Sublime Text from the command line by utilizing the subl command

git 명령어

[gRPC] server of Java and client of Typescript

[Ubuntu] Apache2.4.x 설치

Create topic on Kafka with partition count, 카프카 토픽 생성하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Auto-populate a calendar in an MUI (Material-UI) TextField component

The pierce selector in Puppeteer