[英]Map dynamic JSON data to pojo class in Java?
[英]Map json data to corresponding Class
我有一个String格式的JSON数据。此JSON数据来自JMS队列。 例如: -
String msg=" {"id":"4","item":"GOT","description":"hello"}";
我正在通过使用Gson库将此JSON字符串转换为对应的类对象
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可以是books表的,也可以是具有json格式的事务表的
String msg=" {"id":"2","name":"deposit","purpose":"savings"}";
我想基于JSON字符串将对象动态映射到相应的类。
例如:如果有JSON图书,则将其发送到Books表;如果有JSON事务,则将其发送到Transaction表。
我怎样才能做到这一点? 如果阿帕奇骆驼可以做到这一点,请告诉如何处理? 任何方法将不胜感激。
首先使用JsonParser
解析JSON,以便您可以对其进行检查,然后使用Gson
解组为适当的对象类型。
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-jsonpath
来检查JSON字符串是否包含某个字段:
<choice>
<when>
<jsonpath suppressExceptions="true">$.item</jsonpath>
<!-- Unmarshal to Book -->
</when>
<when>
<jsonpath suppressExceptions="true">$.name</jsonpath>
<!-- Unmarshal to Transaction -->
</when>
</choice>
您可以尝试签出骆驼的扩展名-JSON模式验证器组件 。 它的工作方式应与骆驼中的原始验证器相同,但是它允许您根据模式验证消息正文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.