操作Json对象的几种方式

84 阅读1分钟

1.使用ObjectMapper

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

public class JsonExample {
    public static void main(String[] args) {
        String jsonString = "{"name": "Alice", "age": 30, "city": "New York"}";
        try { // 将 JSON 字符串解析为 JsonNode 对象 
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            // 获取节点值 
            String name = jsonNode.get("name").asText();
            int age = jsonNode.get("age").asInt();
            String city = jsonNode.get("city").asText();
            // 打印节点值 
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("City: " + city);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.使用Gson

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class JsonExample {
    public static void main(String[] args) {
        String jsonString = "{"name": "Alice", "age": 30, "city": "New York"}";
        
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
        
        String name = jsonObject.get("name").getAsString();
        int age = jsonObject.get("age").getAsInt();
        String city = jsonObject.get("city").getAsString();
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
    }
}

3.使用fastjson

import com.alibaba.fastjson.JSONObject;

public class JsonExample {
    public static void main(String[] args) {
        String jsonString = "{"name": "Alice", "age": 30, "city": "New York"}";
        
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        
        String name = jsonObject.getString("name");
        int age = jsonObject.getInteger("age");
        String city = jsonObject.getString("city");
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
    }
}