【问题标题】:MulitvaluedMap<String, String> to MultivaluedMap<String, Object>MultivaluedMap<String, String> 到 MultivaluedMap<String, Object>
【发布时间】:2020-02-06 05:49:13
【问题描述】:

我有一个MultivaluedMap&lt;String, String&gt; strMap,我想将其转换为MultivaluedMap&lt;String, Object&gt; objMap

我尝试在下面的帖子中探索几条路线,但似乎没有一条可行。

Converting Map<String,String> to Map<String,Object>

【问题讨论】:

  • “似乎有效”是什么意思?你没有测试过它们吗?为什么不呢?
  • 你能添加你的代码和问题/错误吗?
  • 你问的是哪个MultivaluedMap
  • 我认为MultivaluedMap 的实现可能像&lt;key, list&lt;string&gt;&gt;。如果将其转换为&lt;key, list&lt;object&gt;&gt;,则必须转换列表中的每个值。
  • @Tom " OP 使用 Apache 实现"? OP 还没有回应,但是如果你看看我引用的两个名字,Apache 实现实际上对Valued 中的V 字符有错误的大小写,所以很可能OP 使用的是JAX-RS 实现,而不是Apache 实现。 --- 除此之外,您所说的“没有必要”是什么意思?有些东西是必要的,并且说“那将是不必要的” 听起来像是有一个更简单 的解决方案,但有什么比宽松的复制构造函数更简单的呢?

标签: java hashmap type-conversion multivalue


【解决方案1】:

我今天遇到了同样的问题,经过大量搜索,我想出了以下解决方案:

public static MultivaluedMap<String, Object> asObjectHeaders(MultivaluedMap<String, String> headers) {
    if (headers == null) {
        return null;
    } else {
        MultivaluedMap<String, Object> map = new MultivaluedHashMap<>();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            if (entry.getValue() != null) {
                map.addAll(entry.getKey(), new LinkedList<Object>(entry.getValue()));
            }
        }
        return map;
    }
}

或者如果您使用的是 Guava,那么您可以使用以下代码:

public static MultivaluedMap<String, Object> asObjectHeaders(MultivaluedMap<String, String> headers) {
    if (headers == null) {
        return null;
    } else {
        return new AbstractMultivaluedMap<String, Object>(Maps.transformValues(headers, new Function<List<String>, List<Object>>() {
            @Override
            public @Nullable List<Object> apply(@Nullable List<String> strings) {
                if (strings != null) {
                    return new LinkedList<>(strings);
                } else {
                    return null;
                }
            }
        })) {};
    }
}

或者如果您使用的是 jersey 客户端 glassfish,那么您可以使用以下内容:

public static MultivaluedMap<String, Object> asObjectHeaders(MultivaluedMap<String, String> headers) {
    if (headers == null) {
        return null;
    } else {
        return new AbstractMultivaluedMap<String, Object>(Views.mapView(headers, LinkedList::new)) {};
    }
}

【讨论】:

    【解决方案2】:

    有同样的情况,工作解决方案-

    MultiValuedMap<String, String> multivaluedMap = //store the value here 
    Collection<Map.Entry<String, String>> entries = multivaluedMap.entries();
    
    for(Map.Entry<String, String> ent : multivaluedMap.entries()){
        entityList.add(ent.getKey()+ " " + ent.getValue());
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-01
      • 2018-09-22
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2013-05-24
      • 2014-01-29
      相关资源
      最近更新 更多