I'm trying to use Jackson to convert a HashMap to a JSON representation.
然而,我看到的所有方法都涉及到写入文件,然后读回它,这似乎真的很低效.我在想,有没有什么办法可以直接做呢?
Here's an example of an instance where I'd like to do it
public static Party readOneParty(String partyName) {
Party localParty = new Party();
if(connection==null) {
connection = new DBConnection();
} try {
String query = "SELECT * FROM PureServlet WHERE PARTY_NAME=?";
ps = con.prepareStatement(query);
ps.setString(1, partyName);
resultSet = ps.executeQuery();
meta = resultSet.getMetaData();
String columnName, value;
resultSet.next();
for(int j=1;j<=meta.getColumnCount();j++) { // necessary to start at j=1 because of MySQL index starting at 1
columnName = meta.getColumnLabel(j);
value = resultSet.getString(columnName);
localParty.getPartyInfo().put(columnName, value); // this is the hashmap within the party that keeps track of the individual values. The column Name = label, value is the value
}
}
}
public class Party {
HashMap <String,String> partyInfo = new HashMap<String,String>();
public HashMap<String,String> getPartyInfo() throws Exception {
return partyInfo;
}
}
输出结果如下所示
"partyInfo": {
"PARTY_NAME": "VSN",
"PARTY_ID": "92716518",
"PARTY_NUMBER": "92716518"
}
到目前为止,我遇到的每一个使用ObjectMapper
的例子都涉及到写入一个文件,然后将其读回.
是否有Java的HashMap
或Map
的Jackson版本可以以与我实现的类似的方式工作?