Java GSON Json 部分解析

Java GSON Json partial parsing

假设我有一个 JSON 对象代表一个实体(可以是任何实体),如下所示:

{
    "entity_id": "1",
    "entity_name": "employee",
    "entity_json": {
        "employee_id": "e01",
        "employee_name": "john",
        "employee_phone_numbers": [
            "1234567",
            "8765433"
        ]
    }
}

请注意,entity_json 可以表示具有不同结构的不同实体,只要它是有效的 JSON。例如,下面是另一个实体的表示:

{
    "entity_id": "1",
    "entity_name": "invoice",
    "entity_json": {
        "invoice_id": "1011",
        "items": {
            "item_id": "1",
            "quantity": "3",
            "price": "0"
        },
        "date": "01-01-2020",
        "customer": {
            "id": "3",
            "address": {
                "street": "some_street",
                "country": "CZ",
                ...
            }
        }
    }
}

我希望能够使用 Java 中的 Gson 将此 JSON 部分解析为实体 POJO。也就是说,我将拥有一个如下所示的实体 POJO:

public class Entity {
    private String entity_id;
    private String entity_name;
    private String entity_json;  // <-- entity_json is a String

    // getters and setters
}


/*
 * entity_json (for employee) = "{ \"employee_id\": \"1\", \"employee... }"
 * entity_json (for invoice) = "{ \"invoice_id\": \"1011\", \"items... }"
 */

并且我计划使用 JsonPath 在 entity_json 上执行任何操作。

有什么方法可以实现这一点而不必在 JSON 结构中将 entity_json 显式设置为带转义的字符串?

在此感谢任何帮助。谢谢!

您可以通过使用 Gson 的 JsonObject.

来避免为您的 entity_json 使用 String

这是我修改后的 Entity class:

import com.google.gson.JsonObject;

public class MyEntity {

    private String entity_id;
    private String entity_name;
    private JsonObject entity_json;

    // getters and setters not shown

}

然后您可以按如下方式填充实例:

MyEntity myEntityOne = new Gson().fromJson(JSON_ONE, MyEntity.class);
MyEntity myEntityTwo = new Gson().fromJson(JSON_TWO, MyEntity.class);

System.out.println(myEntityOne.getEntity_json());
System.out.println(myEntityTwo.getEntity_json());

在上面的代码中,JSON_ONEJSON_TWO 只是包含您问题中的两个样本 JSON 的字符串。

控制台打印出以下内容(为简洁起见被截断):

{"employee_id":"e01","employee_name":"john","employee_phone_numbers":["1234567","8765433"]}
{"invoice_id":"1011","items":{"item_id":"1","quantity":"3","price":"0"},"date":"01-01-2020"...

当然,您现在可以根据需要使用 Gson 进一步操作每个 entity_json 字段,因为每个字段本身都是一个有效的 JSON 对象。