【问题标题】:Parse String into Java Objects将字符串解析为 Java 对象
【发布时间】: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(),所以看起来我需要手动解析包含ArrayStructs 的列。不幸的是,这是数据库的限制,我无法控制它。这是我在列上调用 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


【解决方案1】:

也许我误解了你的问题,但如果你稍微清理一下,你输入的内容应该可以工作,如下所示:

[{ name:"Nany Chapman", email:"nchapman0@comcast.net"}, 
{ name:"Nany Chapman", email:"nchapman0@comcast.net"}]

不要使用等号,而是使用冒号并在值周围加上引号。

【讨论】:

  • 要将其解析为 JSON,还必须在键周围加上引号。
  • 很遗憾,我无法将输入更改为 JSON。我希望我可以这样我就可以利用像 GSON 这样的库
猜你喜欢
  • 2012-05-17
  • 1970-01-01
  • 2023-03-28
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2012-09-28
相关资源
最近更新 更多