JSON-B / JSON-P: From TextBlock To JsonArray

You can directly convert Java TextBlocks to JsonArray with Jakarta JSON Binding (JSON-B) and Jakarta JSON Processing (JSON-P):


import org.junit.jupiter.api.Test;
import jakarta.json.JsonArray;
import jakarta.json.JsonObject;
import jakarta.json.bind.JsonbBuilder;

public class TextBlockToJsonArray {

    @Test
    public void deserializeTextBlock() {
        var input = """
            [
                {
                    "name": "java",
                    "age": 25
                },
                {
                    "name": "python",
                    "age": 52
                
                }]
                """;
        var  jsonArray = JsonbBuilder.create().fromJson(input, JsonArray.class);
        
        //output
        jsonArray.getValuesAs(JsonObject.class).forEach(System.out::println);
    }
    
}

The output:


{"name":"java","age":25}
{"name":"python","age":52}

JSON-B and JSON-P functionality comes as a single dependency:


<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>2.0.4</version>
</dependency>

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments
License