2024/10/21

Java Json library: Jackson, Gson Tree Model

因為 Json 文件本身就是一個樹狀結構,處理 JSON 的 libary 都有對應可處理每一個 json property node 的工具,以下記錄如何使用 Jackson 與 Gson,對 json 做 pretty print,parsing 每個節點,新增/移除節點的方法。

pom

在 pom.xml 加上兩個 libary 的來源

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

        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10.1</version>
        </dependency>

Gson

package json;
import com.google.gson.*;

public class GsonTester {
    public static void main(String args[]) {

        String jsonString =
                "{\"name\":\"John Lin\", \"age\":21,\"verified\":false,\"geo\": [100.11,90.85]}";
//        System.out.println("jsonString="+jsonString);

        // 以 JsonParser parsing 後,取得 JsonObject
        JsonObject details = JsonParser.parseString(jsonString).getAsJsonObject();

        //************/
        // pretty print json string
//            {
//                "name" : "John Lin",
//                "age" : 21,
//                "verified" : false,
//                "geo" : [
//                    100.11,
//                    90.85
//                ]
//            }
//        System.out.println(details.toString());

        System.out.println();
        System.out.println("*** original Json");
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonOutput = gson.toJson(details);
        System.out.println(jsonOutput);

        //************/
        // parsing json
        System.out.println();
        System.out.println("*** parsing Json");
        if (details.isJsonObject()) {
            // JsonElement 對應 "name":"John Lin"
            JsonElement nameNode = details.get("name");
            System.out.println("Name: " +nameNode.getAsString());

            JsonElement ageNode = details.get("age");
            System.out.println("Age: " + ageNode.getAsInt());

            JsonElement verifiedNode = details.get("verified");
            System.out.println("Verified: " + (verifiedNode.getAsBoolean() ? "Yes":"No"));

            // JsonArray 對應 [100.11,90.85]
            JsonArray geoNode = details.getAsJsonArray("geo");
            System.out.print("geo: ");
            for (int i = 0; i < geoNode.size(); i++) {
                JsonPrimitive value = geoNode.get(i).getAsJsonPrimitive();
                System.out.print(value.getAsFloat() + " ");
            }
            System.out.println();
        }

        //************/
        // add/remove property
        System.out.println();
        System.out.println("*** new Json After add/remove property");
        details.addProperty("school", "Tsing-Hua");
        details.remove("verified");
        String jsonOutput2 = gson.toJson(details);
        System.out.println(jsonOutput2);
    }
}

Jackson

package json;

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.ObjectNode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;

public class JacksonTest {
    public static void main(String args[]) {
        try {
            String jsonString =
                    "{\"name\":\"John Lin\", \"age\":21,\"verified\":false,\"geo\": [100.11,90.85]}";
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonObject = mapper.readTree(jsonString);

            //************/
            // pretty print json string
//            {
//                "name" : "John Lin",
//                    "age" : 21,
//                    "verified" : false,
//                    "geo" : [ 100.11, 90.85 ]
//            }
            System.out.println();
            System.out.println("*** original Json");
            String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
            System.out.println(prettyJson);

            //************/
            // parsing json
            System.out.println();
            System.out.println("*** parsing Json");
            JsonNode jsonNodeName = jsonObject.get("name");
            System.out.println("Name: " +jsonNodeName.asText() );

            JsonNode jsonNodeAge = jsonObject.get("age");
            System.out.println("Age: " + jsonNodeAge.asInt());

            JsonNode jsonNodeVerified = jsonObject.get("verified");
            System.out.println("Verified: " + (jsonNodeVerified.asBoolean() ? "Yes":"No"));

            JsonNode jsonNodeGeo = jsonObject.get("geo");
            System.out.print("geo: ");
            for (int i = 0; i < jsonNodeGeo.size(); i++) {
                double value = jsonNodeGeo.get(i).asDouble();
                System.out.print(value + " ");
            }
            System.out.println();

            //************/
            // add/remove property
            System.out.println();
            System.out.println("*** new Json After add/remove property");
            ObjectNode jsonObject2 = ((ObjectNode) jsonObject).put("school", "Tsing-Hua");
            JsonNode removedNode = jsonObject2.remove("verified" );
            String prettyJson2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject2);
            System.out.println(prettyJson2);

        } catch (JsonProcessingException e1) {

        }
    }
}

結果

*** original Json
{
  "name" : "John Lin",
  "age" : 21,
  "verified" : false,
  "geo" : [ 100.11, 90.85 ]
}

*** parsing Json
Name: John Lin
Age: 21
Verified: No
geo: 100.11 90.85 

*** new Json After add/remove property
{
  "name" : "John Lin",
  "age" : 21,
  "geo" : [ 100.11, 90.85 ],
  "school" : "Tsing-Hua"
}

References

Gson - Tree Model

Working with Tree Model Nodes in Jackson | Baeldung

Jackson - Marshall String to JsonNode | Baeldung

Pretty-Print a JSON in Java | Baeldung

沒有留言:

張貼留言