Java 如何使用 Jackson JSON 将 JSON 字符串转换为 Map<String, String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2525042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:50:14  来源:igfitidea点击:

How to convert a JSON string to a Map<String, String> with Hymanson JSON

javaHymanson

提问by adamJLev

I'm trying to do something like this but it doesn't work:

我正在尝试做这样的事情,但它不起作用:

Map<String, String> propertyMap = new HashMap<String, String>();

propertyMap = HymansonUtils.fromJSON(properties, Map.class);

But the IDE says:

但是IDE说:

Unchecked assignment Map to Map<String,String>

未经检查的分配 Map to Map<String,String>

What's the right way to do this? I'm only using Hymanson because that's what is already available in the project, is there a native Java way of converting to/from JSON?

这样做的正确方法是什么?我只使用 Hymanson 因为这是项目中已经可用的东西,是否有本地 Java 方式来转换为 JSON 或从 JSON 转换?

In PHP I would simply json_decode($str)and I'd get back an array. I need basically the same thing here.

在 PHP 中,我会简单地json_decode($str)返回一个数组。我在这里需要基本相同的东西。

采纳答案by djna

I've got the following code:

我有以下代码:

public void testHymanson() throws IOException {  
    ObjectMapper mapper = new ObjectMapper(); 
    File from = new File("albumnList.txt"); 
    TypeReference<HashMap<String,Object>> typeRef 
            = new TypeReference<HashMap<String,Object>>() {};

    HashMap<String,Object> o = mapper.readValue(from, typeRef); 
    System.out.println("Got " + o); 
}   

It's reading from a file, but mapper.readValue()will also accept an InputStreamand you can obtain an InputStreamfrom a string by using the following:

它正在从文件中读取,但mapper.readValue()也会接受 anInputStream并且您可以InputStream使用以下命令从字符串中获取 an :

new ByteArrayInputStream(astring.getBytes("UTF-8")); 

There's a bit more explanation about the mapper on my blog.

我的博客上有更多关于映射器的解释。

回答by StaxMan

Warning you get is done by compiler, not by library (or utility method).

您收到的警告是由编译器完成的,而不是由库(或实用程序方法)完成的。

Simplest way using Hymanson directly would be:

直接使用 Hymanson 的最简单方法是:

HashMap<String,Object> props;

// src is a File, InputStream, String or such
props = new ObjectMapper().readValue(src, new TypeReference<HashMap<String,Object>>() {});
// or:
props = (HashMap<String,Object>) new ObjectMapper().readValue(src, HashMap.class);
// or even just:
@SuppressWarnings("unchecked") // suppresses typed/untype mismatch warnings, which is harmless
props = new ObjectMapper().readValue(src, HashMap.class);

Utility method you call probably just does something similar to this.

您调用的实用程序方法可能只是执行与此类似的操作。

回答by Ning Sun

Try TypeFactory. Here's the code for Hymanson JSON (2.8.4).

试试TypeFactory。这是 Hymanson JSON (2.8.4) 的代码。

Map<String, String> result;
ObjectMapper mapper;
TypeFactory factory;
MapType type;

factory = TypeFactory.defaultInstance();
type    = factory.constructMapType(HashMap.class, String.class, String.class);
mapper  = new ObjectMapper();
result  = mapper.readValue(data, type);

Here's the code for an older version of Hymanson JSON.

这是旧版本的 Hymanson JSON 的代码。

Map<String, String> result = new ObjectMapper().readValue(
    data, TypeFactory.mapType(HashMap.class, String.class, String.class));

回答by Raja

Converting from String to JSON Map:

从字符串转换为 JSON 映射:

Map<String,String> map = new HashMap<String,String>();

ObjectMapper mapper = new ObjectMapper();

map = mapper.readValue(string, HashMap.class);

回答by dpetruha

ObjectReader reader = new ObjectMapper().readerFor(Map.class);

Map<String, String> map = reader.readValue("{\"foo\":\"val\"}");

Note that readerinstance is Thread Safe.

请注意,reader实例是线程安全的。

回答by HymanieZhi

JavaType javaType = objectMapper.getTypeFactory().constructParameterizedType(Map.class, Key.class, Value.class);
Map<Key, Value> map=objectMapper.readValue(jsonStr, javaType);

i think this will solve your problem.

我认为这将解决您的问题。

回答by Brad Parks

The following works for me:

以下对我有用:

Map<String, String> propertyMap = getJsonAsMap(json);

where getJsonAsMapis defined like so:

其中getJsonAsMap定义如下:

public HashMap<String, String> getJsonAsMap(String json)
{
    try
    {
        ObjectMapper mapper = new ObjectMapper();
        TypeReference<Map<String,String>> typeRef = new TypeReference<Map<String,String>>() {};
        HashMap<String, String> result = mapper.readValue(json, typeRef);

        return result;
    }
    catch (Exception e)
    {
        throw new RuntimeException("Couldnt parse json:" + json, e);
    }
}

Note that this willfail if you have child objects in your json (because they're not a String, they're another HashMap), but will work if your json is a key value list of properties like so:

请注意,如果您的 json 中有子对象(因为它们不是 a ,它们是 another ),这失败,但如果您的 json 是属性的键值列表,则会起作用,如下所示:StringHashMap

{
    "client_id": "my super id",
    "exp": 1481918304,
    "iat": "1450382274",
    "url": "http://www.example.com"
}

回答by Loukan ElKadi

Using Google's Gson

使用谷歌的 Gson

Why not use Google's Gson as mentioned in here?

为什么不使用此处提到的 Google 的 Gson ?

Very straight forward and did the job for me:

非常直接,为我完成了这项工作:

HashMap<String,String> map = new Gson().fromJson( yourJsonString, new TypeToken<HashMap<String, String>>(){}.getType());

回答by NameNotFoundException

Here is the generic solution to this problem.

这是此问题的通用解决方案。

public static <K extends Object, V extends Object> Map<K, V> getJsonAsMap(String json, K key, V value) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      TypeReference<Map<K, V>> typeRef = new TypeReference<Map<K, V>>() {
      };
      return mapper.readValue(json, typeRef);
    } catch (Exception e) {
      throw new RuntimeException("Couldnt parse json:" + json, e);
    }
  }

Hope someday somebody would think to create a util method to convert to any Key/value type of Map hence this answer :)

希望有一天有人会考虑创建一个 util 方法来转换为 Map 的任何键/值类型,因此这个答案:)

回答by Dustin

just wanted to give a Kotlin answer

只是想给出一个 Kotlin 答案

val propertyMap = objectMapper.readValue<Map<String,String>>(properties, object : TypeReference<Map<String, String>>() {})