【发布时间】:2017-03-10 20:26:56
【问题描述】:
我需要将这种格式的Strings 转换为对象的Array。
[{name=Nancy Chapman, email=nchapman0@comcast.net}, {name=Jimmy Fisher, email=jfisher1@photobucket.com}]
有什么简单的方法可以不用完全手动进行转换吗?
更新:
我从自定义 SQL 数据库 (Amazon Athena) 中提取这些值。并且自定义JDBC 不支持getArray(),所以看起来我需要手动解析包含Array 的Structs 的列。不幸的是,这是数据库的限制,我无法控制它。这是我在列上调用 getString() 时 SQL 数据库返回的格式。
SQL 表定义
id (int)
threadid (int)
senderemail (string)
sendername (string)
subject (string)
body (string)
recipients (array<struct<name:string,email:string>>)
ccrecipients (array<struct<name:string,email:string>>)
bccrecipients (array<struct<name:string,email:string>>)
attachments (array<binary>)
date (timestamp)
Java 对象
MessageObj
public class MessageObj {
private int id;
private int threadId;
private String senderEmail;
private String senderName;
private String subject;
private String body;
private List<RecipientObj> recipients;
private List<RecipientObj> ccRecipients;
private List<RecipientObj> bccRecipients;
private List<File> attachments;
private Calendar date;
}
RecipientObj
public class RecipientObj {
private String email;
private String name;
}
解析数据。
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// Retrieve table column.
int id = rs.getInt("id");
Integer threadId = rs.getInt("threadid");
String senderEmail = rs.getString("senderemail");
String senderName = rs.getString("sendername");
String subject = rs.getString("subject");
String body = rs.getString("body");
//How to convert recipients into ArrayList? rs.getArray("recipients") not supported.
//... Code here to add into an ArrayList of MessageObj.
}
【问题讨论】:
-
为什么你的输入是这种格式?他们来自哪里?它看起来有点像损坏的 JSON;是否涉及 JSON?
-
格式有名称吗?如果它很常见,则可能有一个库,否则您将不得不手动完成或使用不同的格式。
-
为什么不遍历 ResultSet 来创建对象数组呢?此外,使用 Hibernate 等框架可以更轻松地将值从 DB 映射到对象。
-
@Alan 我相信您将不得不手动进行数据绑定。由于 Athena 是一个大数据数据服务器,Hibernate 或任何其他 JPA 框架都无法工作。所以你可能需要手动完成。
标签: java sql arrays jdbc amazon-athena