【问题标题】:How to convert Map into javax.json.JsonObject?如何将 Map 转换为 javax.json.JsonObject?
【发布时间】:2019-09-22 02:45:37
【问题描述】:

我可以这样做:

Map<String, String> mapA = ...;
Map<String, String> mapB = mapA.entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue
    ));

但是当我尝试这样做时:

... mapA.entrySet().stream()
    .collect(JsonCollectors.toJsonObject(
        JsonObject.Entry::getKey,
        JsonObject.Entry::getValue
    ));

我明白了

不能从静态上下文中引用非静态方法

对于JsonObject.Entry::getKey, JsonObject.Entry::getValue 部分。

为什么?

【问题讨论】:

  • 你这样做的目的是什么?
  • JSON 对象将成为application/json HTTP 响应的一部分。
  • 在什么情况下?我知道的每个平台(Spring、Micronaut、Dropwizard、Jersey)都支持返回一个常规对象,并自动为您完成所有这些。
  • 没有框架,只有java SE,com.sun.net.httpserver

标签: java lambda javax.json


【解决方案1】:

您可以使用add method of JsonObjectBuilder:

JsonObjectBuilder builder = Json.createObjectBuilder();
mapA.forEach(builder::add);
JsonObject obj = builder.build();

【讨论】:

  • 这是我认为最简单的解决方案。
【解决方案2】:

javax.json.JsonObjectMap&lt;String,JsonValue&gt; 的子类,所以它有putAll 方法

void putAll(Map<? extends K,? extends V> m)

所以您可以创建JsonObject 并添加Map

JsonObject object = Json.createObjectBuilder().build();
object.putAll(mapA);

【讨论】:

  • 谢谢,我试过了,它可以工作,但地图必须是&lt;String, JsonValue&gt;
【解决方案3】:

使用 org.json 代替 javax.json

// Create a JSON object directly from your map
JSONObject obj = new JSONObject( srcmap );
// Convert it into string
String data = obj.toString();

【讨论】:

  • 谢谢,org.json 很简洁,但是 javax.json 已经在应用程序中到处使用了,我无法替换它。
  • 你可以试试我的回答@tom
猜你喜欢
  • 2021-07-13
  • 1970-01-01
  • 2016-10-12
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
相关资源
最近更新 更多