问题描述
我正在尝试使用 Jackson 将 HashMap 转换为 JSON 表示.
I'm trying to use Jackson to convert a HashMap to a JSON representation.
然而,我见过的所有方法都涉及写入文件然后读回,这似乎非常低效.我想知道是否有办法直接做到这一点?
However, all the ways I've seen involve writing to a file and then reading it back, which seems really inefficient. I was wondering if there was anyway to do it directly?
这是我想做的一个例子
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
的示例都涉及写入文件然后读取它.
So far every example I've come across of using ObjectMapper
involves writing to a file and then reading it back.
是否有 Java 的 HashMap
或 Map
的 Jackson 版本,其工作方式与我已实现的方式类似?
Is there a Jackson version of Java's HashMap
or Map
that'll work in a similar way to what I have implemented?
推荐答案
Pass your Map to ObjectMapper.writeValueAsString(Object value)
Pass your Map to ObjectMapper.writeValueAsString(Object value)
它比使用 StringWriter
更高效,根据文档:
It's more efficient than using StringWriter
, according to the docs:
可用于将任何 Java 值序列化为字符串的方法.功能上相当于用StringWriter调用writeValue(Writer,Object)并构造String,但效率更高.
示例
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) throws IOException {
Map<String,String> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
String mapAsJson = new ObjectMapper().writeValueAsString(map);
System.out.println(mapAsJson);
}
}
这篇关于有没有办法在不写入文件的情况下使用 Jackson 将 Map 转换为 JSON 表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!