有没有办法在没有写入文件的情况下使用Jackson将Map转换为JSON表示?

时间:2013-07-23 19:49:07

标签: java json jackson

我正在尝试使用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 HashMapMap是否会以与我实施的相似的方式运作?

2 个答案:

答案 0 :(得分:68)

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

它比使用StringWriteraccording to the docs更有效:

  

可用于将任何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);
    }
}

答案 1 :(得分: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"}