33

我正在尝试使用 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涉及写入文件然后将其读回。

是否有 Java 的 Jackson 版本,HashMap或者Map它的工作方式与我实现的类似?

4

2 回答 2

70

将您的地图传递给ObjectMapper.writeValueAsString(Object value)

根据文档StringWriter,它比 using 更有效:

可用于将任何 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);
    }
}
于 2013-07-23T21:32:24.373 回答
8

您可以使用 StringWriter。

package test;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class StringWriterExample {

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws IOException {

        Map<String,String> map = new HashMap<>();
        map.put("key1","value1");
        map.put("key2","value2");

        StringWriter stringWriter = new StringWriter();

        objectMapper.writeValue(stringWriter, map);

        System.out.println(stringWriter.toString());
    }
}

生产

{"key2":"value2","key1":"value1"}
于 2013-07-23T20:01:38.340 回答