如何将 JSON 字符串转换为 Map与杰克逊 JSON

发布于 2024-08-26 07:55:19 字数 449 浏览 6 评论 0原文

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

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

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

但是 IDE 说:

未经检查的分配映射到映射

执行此操作的正确方法是什么? 我只使用 Jackson,因为这是项目中已经可用的,是否有本地 Java 方式来转换 JSON?

在 PHP 中,我只需 json_decode($str) 即可返回一个数组。我这里需要基本上相同的东西。

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

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

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

But the IDE says:

Unchecked assignment Map to Map<String,String>

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

眼泪也成诗 2024-09-02 07:55:19

[2020 年 9 月更新]虽然我多年前的原始答案似乎很有帮助并且仍在获得支持,但我现在使用 Google 的 GSON 库,我发现它更直观。

我有以下代码:

public void testJackson() 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); 
}   

它正在从文件中读取,但是 mapper.readValue() 也将接受 InputStream 并且您可以获得 InputStream code> 使用以下内容从字符串中获取:

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

我的博客

[Update Sept 2020] Although my original answer here, from many years ago, seems to be helpful and is still getting upvotes, I now use the GSON library from Google, which I find to be more intuitive.

I've got the following code:

public void testJackson() 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 InputStream and you can obtain an InputStream from a string by using the following:

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

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

寻找一个思念的角度 2024-09-02 07:55:19

尝试TypeFactory。这是 Jackson 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);

以下是旧版本 Jackson JSON 的代码。

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

Try TypeFactory. Here's the code for Jackson 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 Jackson JSON.

Map<String, String> result = new ObjectMapper().readValue(
    data, TypeFactory.mapType(HashMap.class, String.class, String.class));
羞稚 2024-09-02 07:55:19

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

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

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

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

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

Simplest way using Jackson directly would be:

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.

眼藏柔 2024-09-02 07:55:19
ObjectReader reader = new ObjectMapper().readerFor(Map.class);

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

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

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

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

Note that reader instance is Thread Safe.

佞臣 2024-09-02 07:55:19

从字符串转换为 JSON 映射:

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

ObjectMapper mapper = new ObjectMapper();

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

Converting from String to JSON Map:

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

ObjectMapper mapper = new ObjectMapper();

map = mapper.readValue(string, HashMap.class);
谈下烟灰 2024-09-02 07:55:19

对于 Kotlin,请使用:

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

或者包含 jackson-module-kotlin

val propertyMap = objectMapper.readValue<Map<String, String>>(properties)

For Kotlin, use:

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

Or with jackson-module-kotlin included:

val propertyMap = objectMapper.readValue<Map<String, String>>(properties)
野の 2024-09-02 07:55:19

以下内容对我有用:

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

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

请注意,如果您的 json 中有子对象,则此将会失败(因为它们不是 String,它们是另一个 HashMap),但如果您的 json 是属性的键值列表,则可以使用,如下所示:

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

The following works for me:

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

where getJsonAsMap is defined like so:

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 will fail 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:

{
    "client_id": "my super id",
    "exp": 1481918304,
    "iat": "1450382274",
    "url": "http://www.example.com"
}
白首有我共你 2024-09-02 07:55:19
JavaType javaType = objectMapper.getTypeFactory().constructParameterizedType(Map.class, Key.class, Value.class);
Map<Key, Value> map=objectMapper.readValue(jsonStr, javaType);

我想这会解决你的问题。

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.

橙幽之幻 2024-09-02 07:55:19

使用 Google 的 Gson

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

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

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

Using Google's Gson

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

Very straight forward and did the job for me:

HashMap<String,String> map = new Gson().fromJson( yourJsonString, new TypeToken<HashMap<String, String>>(){}.getType());
吻风 2024-09-02 07:55:19

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

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

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

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 :)

梦屿孤独相伴 2024-09-02 07:55:19

Kotlin 的示例代码。

class HeathCheckController {
    fun get(): Any {
        val config = this::class.java.getResource("/git-info.yml")?.readText()
        return ObjectMapper()
            .readValue(config, Map::class.java)
    }
}

摇篮

val jackson = "2.13.2"

Sample code for Kotlin.

class HeathCheckController {
    fun get(): Any {
        val config = this::class.java.getResource("/git-info.yml")?.readText()
        return ObjectMapper()
            .readValue(config, Map::class.java)
    }
}

Gradle

val jackson = "2.13.2"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文