将 json 数据映射到相应的 Class

Map json data to corresponding Class

我有一个 JSON 字符串中的数据 format.This JSON 数据来自 JMS 队列。 例如:-

String msg=" {"id":"4","item":"GOT","description":"hello"}";

我正在使用 Gson 库

将此 JSON 字符串转换为对应的 class 对象
Gson g = new Gson();   
BooksTable b1 = g.fromJson(msg, BooksTable.class); //BooksTable is a POJO class with getter setters
addBook(b1);   //used to insert object into the database Books table

现在的问题是这个 json 可以是书籍 table 或交易 table 的 json 格式

String msg=" {"id":"2","name":"deposit","purpose":"savings"}";

我想根据 JSON 字符串将对象动态映射到相应的 classes。

例如:如果 Books JSON 出现,则将其发送至 Books table 如果 Transaction JSON 出现,则将其发送至 Transaction table.

我该怎么做?如果 apache camel 可以做到这一点请告诉如何处理? 任何方法将不胜感激。

首先使用 JsonParser, so you can examine it, then unmarshal to the appropriate object type using Gson 解析 JSON。

public class Test {
    public static void main(String[] args) {
        process("{\"id\":\"4\",\"item\":\"GOT\",\"description\":\"hello\"}");
        process("{\"id\":\"2\",\"name\":\"deposit\",\"purpose\":\"savings\"}");
    }
    private static void process(String json) {
        JsonObject object = new JsonParser().parse(json).getAsJsonObject();
        if (object.has("item")) {
            Book book = new Gson().fromJson(object, Book.class);
            System.out.println(book);
        } else if (object.has("name")) {
            Transaction transaction = new Gson().fromJson(object, Transaction.class);
            System.out.println(transaction);
        } else {
            System.out.println("Unknown JSON: " + json);
        }
    }
}
class Book {
    private int id;
    private String item;
    private String description;
    @Override
    public String toString() {
        return "Book[id=" + this.id +
                  ", item=" + this.item +
                  ", description=" + this.description + "]";
    }
}
class Transaction {
    private int id;
    private String name;
    private String purpose;
    @Override
    public String toString() {
        return "Transaction[id=" + this.id +
                         ", name=" + this.name +
                         ", purpose=" + this.purpose + "]";
    }
}

输出

Book[id=4, item=GOT, description=hello]
Transaction[id=2, name=deposit, purpose=savings]

您可以尝试查看此 camel 扩展 -- JSON Schema Validator Component。它应该与 camel 中的原始验证器一样工作,但它允许您根据模式验证消息正文。

您可以使用 camel-jsonpath 检查 JSON 字符串是否包含特定字段:

<choice>
    <when>
        <jsonpath suppressExceptions="true">$.item</jsonpath>
        <!-- Unmarshal to Book -->
    </when>
    <when>
        <jsonpath suppressExceptions="true">$.name</jsonpath>
        <!-- Unmarshal to Transaction -->
    </when>
</choice>