簡體   English   中英

Java GSON Json部分解析

[英]Java GSON Json partial parsing

假設我有一個 JSON object 代表一個實體(可以是任何實體),如下所示:

{
    "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": "$100"
        },
        "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執行任何操作。

有什么方法可以實現這一點,而不必將entity_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":"$100"},"date":"01-01-2020"...

當然,您現在可以根據需要使用 Gson 進一步操作每個entity_json字段,因為每個字段本身都是有效的 JSON object。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM