我正在尝试使用Jackson将HashMap转换为JSON表示形式。
但是,我所见过的所有方法都涉及写入文件然后再读回,这似乎效率很低。我想知道是否有直接做的办法?
这是我想做的一个例子
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涉及到写入文件然后将其读回。
ObjectMapper
是否有杰克逊(Jackson)版本的Java HashMap或Map将以与我已实现的方式相似的方式工作?
HashMap
Map
将您的地图传递给 ObjectMapper.writeValueAsString(Object value)
ObjectMapper.writeValueAsString(Object value)
根据docsStringWriter,它比使用效率更高:
StringWriter
可用于将任何Java值序列化为String的方法。在功能上等效于使用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); } }