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的HashMapMap的Jackson版本可以以与我实现的类似的方式工作?

推荐答案

Pass your Map to ObjectMapper.writeValueAsString(Object value)

It's more efficient than using StringWriter, according to the docs:

Method that can be used to serialize any Java value as a String. Functionally equivalent to calling writeValue(Writer,Object) with StringWriter and constructing String, but more efficient.

Example

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);
    }
}

Json相关问答推荐

如何在JMESPath中区分空和假?

从JSON格式提取数据时分隔通用名称

震击:三针并用震击

在解码的JSON哈希中搜索数组元素

在ConvertFrom-Json之后需要从PowerShell对象中获取数据

如何用JQ更改空/布尔/数字的 colored颜色 ?

处理输入数据并转换为更简单的格式-PowerBI

如何在Swift中使用JSON编码器的泛型

为什么 Django Rest API 序列化器没有正确序列化多对多字段

Golang jsonrpc2 服务器在哪里监听?

JSON 的自定义编组器,可以是字符串或 map[string]string / map[string]bool

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

如何为包含一些固定值并可能具有其他附加值的数组字符串创建数组 json 架构

按 JSON 数据类型 postgres 排序

Jackson 中的 readValue 和 readTree:何时使用哪个?

消息通知产生此内容无法显示

字符串的 Gson 数组到 JsonArray

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

区分字符串和列表的 Pythonic 方式是什么?

如何在 React js 中解析本地 JSON 文件?