从json字符串中获取指定值

目录

[一、 FastJSON](#一、 FastJSON)

[1)解析 JSON 字符串为 Java 对象](#1)解析 JSON 字符串为 Java 对象)

[2)处理嵌套的 JSON 结构(创建java对象)](#2)处理嵌套的 JSON 结构(创建java对象))

[3)处理嵌套的 JSON 结构(直接从 JSON 对象中获取值)](#3)处理嵌套的 JSON 结构(直接从 JSON 对象中获取值))

[4)处理嵌套的 JSON 结构(使用路径表达式)](#4)处理嵌套的 JSON 结构(使用路径表达式))

二、Jackson

1)创建java对象

[2)直接从 JSON 对象中获取值](#2)直接从 JSON 对象中获取值)

三、Gson

[1)解析为 Java 对象](#1)解析为 Java 对象)

[2)直接从 JSON 对象中获取值](#2)直接从 JSON 对象中获取值)

四、org.json

1)解析为JSONObject对象

[2)使用递归遍历 JSON 对象](#2)使用递归遍历 JSON 对象)


一、 FastJSON

1)解析 JSON 字符串为 Java 对象

存在一个json字符串:{"name":"John","age":30,"isStudent":false}

//定义一个 Java 类来对应这个 JSON 结构
class Person {
    private String name;
    private int age;
    private boolean isStudent;

    // 生成相应的 getter 和 setter 方法
}

直接从 JSON 对象中获取值

import com.alibaba.fastjson.JSONObject;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"name\":\"John\",\"age\":30,\"isStudent\":false}";
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String name = jsonObject.getString("name");
        int age = jsonObject.getInteger("age");
        boolean isStudent = jsonObject.getBooleanValue("isStudent");

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Is Student: " + isStudent);
    }
}
2)处理嵌套的 JSON 结构(创建java对象)

已知存在一个josn:{"person":{"name":"John","age":30},"address":{"city":"New York","country":"USA"}}

//定义对应的 Java 类
class Person {
    private String name;
    private int age;

    // getter 和 setter 方法
}

class Address {
    private String city;
    private String country;

    // getter 和 setter 方法
}

class RootObject {
    private Person person;
    private Address address;

    // getter 和 setter 方法
}

解析:

import com.alibaba.fastjson.JSON;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"person\":{\"name\":\"John\",\"age\":30},\"address\":{\"city\":\"New York\",\"country\":\"USA\"}}";
        RootObject rootObject = JSON.parseObject(jsonStr, RootObject.class);
        Person person = rootObject.getPerson();
        Address address = rootObject.getAddress();

        String name = person.getName();
        int age = person.getAge();
        String city = address.getCity();
        String country = address.getCountry();

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}
3)处理嵌套的 JSON 结构(直接从 JSON 对象中获取值

存在json串:

{"user":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

import com.alibaba.fastjson.JSONObject;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"user\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
        JSONObject jsonObject = JSON.parseObject(jsonStr);

        JSONObject userObject = jsonObject.getJSONObject("user");
        String userName = userObject.getString("name");
        int userAge = userObject.getInteger("age");

        JSONObject addressObject = userObject.getJSONObject("address");
        String city = addressObject.getString("city");
        String country = addressObject.getString("country");

        JSONArray ordersArray = jsonObject.getJSONArray("orders");
        for (int i = 0; i < ordersArray.size(); i++) {
            JSONObject orderObject = ordersArray.getJSONObject(i);
            int orderId = orderObject.getInteger("id");
            String product = orderObject.getString("product");
            System.out.println("Order ID: " + orderId + ", Product: " + product);
        }

        System.out.println("User Name: " + userName);
        System.out.println("User Age: " + userAge);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}
4)处理嵌套的 JSON 结构(使用路径表达式

存在json串:

{"user":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

import com.alibaba.fastjson.JSONPath;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"user\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";

        String userName = (String) JSONPath.read(jsonStr, "$.user.name");
        int userAge = (int) JSONPath.read(jsonStr, "$.user.age");
        String city = (String) JSONPath.read(jsonStr, "$.user.address.city");
        String country = (String) JSONPath.read(jsonStr, "$.user.address.country");

        Object[] orders = JSONPath.read(jsonStr, "$.orders");
        for (Object order : orders) {
            int orderId = (int) JSONPath.read(order, "$.id");
            String product = (String) JSONPath.read(order, "$.product");
            System.out.println("Order ID: " + orderId + ", Product: " + product);
        }

        System.out.println("User Name: " + userName);
        System.out.println("User Age: " + userAge);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}

二、Jackson

1)创建java对象

已知存在json串:

{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

class Address {
    private String city;
    private String country;

    // Getters and setters
}

class Order {
    private int id;
    private String product;

    // Getters and setters
}

class Person {
    private String name;
    private int age;
    private Address address;

    // Getters and setters
}

class RootObject {
    private Person person;
    private Order[] orders;

    // Getters and setters
}

使用 Jackson 进行解析到对象中

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
        ObjectMapper objectMapper = new ObjectMapper();
        RootObject rootObject = objectMapper.readValue(jsonStr, RootObject.class);

        String name = rootObject.getPerson().getName();
        int age = rootObject.getPerson().getAge();
        String city = rootObject.getPerson().getAddress().getCity();
        String country = rootObject.getPerson().getAddress().getCountry();

        Order[] orders = rootObject.getOrders();
        for (Order order : orders) {
            int orderId = order.getId();
            String product = order.getProduct();
            System.out.println("Order ID: " + orderId + ", Product: " + product);
        }

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}
2)直接从 JSON 对象中获取值

已知存在json串:

{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

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

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonStr);

        JsonNode personNode = rootNode.get("person");
        String name = personNode.get("name").asText();
        int age = personNode.get("age").asInt();

        JsonNode addressNode = personNode.get("address");
        String city = addressNode.get("city").asText();
        String country = addressNode.get("country").asText();

        JsonNode ordersNode = rootNode.get("orders");
        for (JsonNode orderNode : ordersNode) {
            int orderId = orderNode.get("id").asInt();
            String product = orderNode.get("product").asText();
            System.out.println("Order ID: " + orderId + ", Product: " + product);
        }

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}

三、Gson

1)解析为 Java 对象

已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

定义对应的 Java 类:

class Address {
    private String city;
    private String country;

    // Getters and setters
}

class Order {
    private int id;
    private String product;

    // Getters and setters
}

class Person {
    private String name;
    private int age;
    private Address address;

    // Getters and setters
}

class RootObject {
    private Person person;
    private Order[] orders;

    // Getters and setters
}

使用 Gson 进行解析:

import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
        Gson gson = new Gson();
        RootObject rootObject = gson.fromJson(jsonStr, RootObject.class);

        String name = rootObject.getPerson().getName();
        int age = rootObject.getPerson().getAge();
        String city = rootObject.getPerson().getAddress().getCity();
        String country = rootObject.getPerson().getAddress().getCountry();

        Order[] orders = rootObject.getOrders();
        for (Order order : orders) {
            int orderId = order.getId();
            String product = order.getProduct();
            System.out.println("Order ID: " + orderId + ", Product: " + product);
        }

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}
2)直接从 JSON 对象中获取值

已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

不创建 Java 对象,直接从 JSON 对象获取值:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
        JsonObject jsonObject = JsonParser.parseString(jsonStr).getAsJsonObject();

        JsonObject personObject = jsonObject.getAsJsonObject("person");
        String name = personObject.get("name").getAsString();
        int age = personObject.get("age").getAsInt();

        JsonObject addressObject = personObject.getAsJsonObject("address");
        String city = addressObject.get("city").getAsString();
        String country = addressObject.get("country").getAsString();

        JsonArray ordersArray = jsonObject.getAsJsonArray("orders");
        for (JsonElement orderElement : ordersArray) {
            JsonObject orderObject = orderElement.getAsJsonObject();
            int orderId = orderObject.get("id").getAsInt();
            String product = orderObject.get("product").getAsString();
            System.out.println("Order ID: " + orderId + ", Product: " + product);
        }

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}

四、org.json

1)解析为 JSONObject****对象

已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

使用org.json解析:

import org.json.JSONArray;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
        JSONObject jsonObject = new JSONObject(jsonStr);

        // 获取 person 对象
        JSONObject personObject = jsonObject.getJSONObject("person");
        String name = personObject.getString("name");
        int age = personObject.getInt("age");

        // 获取 address 对象
        JSONObject addressObject = personObject.getJSONObject("address");
        String city = addressObject.getString("city");
        String country = addressObject.getString("country");

        // 获取 orders 数组
        JSONArray ordersArray = jsonObject.getJSONArray("orders");
        for (int i = 0; i < ordersArray.length(); i++) {
            JSONObject orderObject = ordersArray.getJSONObject(i);
            int orderId = orderObject.getInt("id");
            String product = orderObject.getString("product");
            System.out.println("Order ID: " + orderId + ", Product: " + product);
        }

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("Country: " + country);
    }
}
2)使用递归遍历 JSON 对象

已知存在json串:已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}

如果 JSON 结构更加复杂,可以使用递归的方式遍历获取值。

import org.json.JSONArray;
import org.json.JSONObject;

public class Main {
    public static void traverseJSON(JSONObject jsonObject) {
        for (String key : JSONObject.getNames(jsonObject)) {
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                traverseJSON((JSONObject) value);
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (int i = 0; i < array.length(); i++) {
                    Object item = array.get(i);
                    if (item instanceof JSONObject) {
                        traverseJSON((JSONObject) item);
                    } else {
                        // 处理基本类型的值
                        System.out.println(key + ": " + item);
                    }
                }
            } else {
                // 处理基本类型的值
                System.out.println(key + ": " + value);
            }
        }
    }

    public static void main(String[] args) {
        String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
        JSONObject jsonObject = new JSONObject(jsonStr);
        traverseJSON(jsonObject);
    }
}
相关推荐
Winston Wood2 分钟前
Java线程池详解
java·线程池·多线程·性能
手握风云-7 分钟前
数据结构(Java版)第二期:包装类和泛型
java·开发语言·数据结构
喵叔哟27 分钟前
重构代码中引入外部方法和引入本地扩展的区别
java·开发语言·重构
尘浮生33 分钟前
Java项目实战II基于微信小程序的电影院买票选座系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea
不是二师兄的八戒1 小时前
本地 PHP 和 Java 开发环境 Docker 化与配置开机自启
java·docker·php
爱编程的小生1 小时前
Easyexcel(2-文件读取)
java·excel
带多刺的玫瑰1 小时前
Leecode刷题C语言之统计不是特殊数字的数字数量
java·c语言·算法
计算机毕设指导62 小时前
基于 SpringBoot 的作业管理系统【附源码】
java·vue.js·spring boot·后端·mysql·spring·intellij-idea
Gu Gu Study2 小时前
枚举与lambda表达式,枚举实现单例模式为什么是安全的,lambda表达式与函数式接口的小九九~
java·开发语言
Chris _data2 小时前
二叉树oj题解析
java·数据结构