用 Java 将 HashMap 写入 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22937888/
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 19:25:51  来源:igfitidea点击:

Write HashMap to JSON in Java

javajson

提问by JQuery Mobile

I'm new to Java. I've been working on a project that uses Maven and Java 1.7. In my project I have a HashMap. I want to output this HashMap to JSON. What is the recommended approach at this time?

我是 Java 新手。我一直在研究一个使用 Maven 和 Java 1.7 的项目。在我的项目中,我有一个 HashMap。我想将此 HashMap 输出到 JSON。目前推荐的方法是什么?

When I do a Google search, I get a lot of options (ie Hymanson). However, I'm not sure what I should be using. Plus, I'd like to use a library that's accessible via Maven.

当我进行 Google 搜索时,我会得到很多选项(即 Hymanson)。但是,我不确定我应该使用什么。另外,我想使用可通过 Maven 访问的库。

Thank you,

谢谢,

采纳答案by David Hofmann

You can use the Google GSONlibrary.

您可以使用Google GSON库。

Just add this to your pom

只需将此添加到您的 pom

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.4</version>
</dependency>

And add this class to your project

并将此类添加到您的项目中

import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

public class JsonHelper {
    private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    private static final Type TT_mapStringString = new TypeToken<Map<String,String>>(){}.getType();

    public static Map<String, String> jsonToMapStringString(String json) {
        Map<String, String> ret = new HashMap<String, String>();
        if (json == null || json.isEmpty())
            return ret;
         return gson.fromJson(json, TT_mapStringString);
    }
    public static String mapStringStringToJson(Map<String, String> map) {
        if (map == null)
            map = new HashMap<String, String>();
         return gson.toJson(map);
    }
}

I guess you can figure it out how to use it

我想你可以弄清楚如何使用它

回答by anirudh

It is true that there are a lot of json parsers for java. Have a look at the json org linkto read about the different json parsers available for java. Also this linkprovides nice and simple tutorials for different json parsers.

确实有很多用于java的json解析器。查看json org 链接以了解可用于 java 的不同 json 解析器。此外,此链接还为不同的 json 解析器提供了漂亮而简单的教程。

Personally I use simple jsonin applications that do not have a lot of json parsing to do and use gsonfor applications that are mostly based on json and hence have to do a lot of json.

我个人simple json在没有很多 json 解析gson的应用程序中使用,并用于主要基于 json 的应用程序,因此必须做很多 json。

回答by Giovanni Botta

You could also use Hymanson, which is in Maven. And you can use it like this:

你也可以使用Hyman逊,这是在Maven的。你可以像这样使用它:

Map<String,Object> map = .... // create a map
ObjectMapper mapper = new ObjectMapper()
String jsonFromMap = mapper.writeValueAsString(map);

Note that the ObjectMapperhas many other methods to read to/from objects.

请注意,ObjectMapper有许多其他方法可以读取/读取对象。

I recommend it because it's easy to use, supports annotations, is production ready and used by many organizations and probably most important, is integrated in many existing framework (Spring, Jersey, RESTeasy, Camel, etc.).

我推荐它是因为它易于使用、支持注释、生产就绪并被许多组织使用,而且可能最重要的是,它集成在许多现有框架中(Spring、Jersey、RESTeasy、Camel 等)。

I am not familiar with GSON, but there is a discussionabout the two you might want to take a look at.

我对 GSON 不熟悉,但有关于您可能想看一看的两者的讨论

回答by leoismyname

if you need to create json from hashmap and if you dont have nested maps :-

如果您需要从 hashmap 创建 json 并且您没有嵌套映射:-

private String createJsonString( Map<String, Object> map) {
    String jsonString = "{ ";
    Set<Map.Entry<String, Object>> entries = map.entrySet();
    for (Map.Entry<String, Object> entry : entries) {

        jsonString = jsonString + "\"" + entry.getKey() + "\"";
        jsonString += " : ";
        jsonString = jsonString + getJsonValue(entry.getValue());
        jsonString += ",  ";
    }
    int i = jsonString.lastIndexOf(",");
    jsonString = jsonString.substring(0, i);
    jsonString += " }";
    return jsonString;
}

private String getJsonValue(Object value) {
    if (value == null) {
        return "";
    } else if (value instanceof Number || value instanceof Boolean) {
        return value.toString();
    } else {
        return "\"" + value + "\"";
    }
}

回答by Valentyn Kolesnikov

Underscore-javalibrary can convert hash map or array list to json and vice verse.

Underscore-java库可以将哈希映射或数组列表转换为 json,反之亦然。

Code example:

代码示例:

import com.github.underscore.lodash.U;
import java.util.*;

public class Main {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {

      Map<String, Object> map = new HashMap<String, Object>();
      map.put("1", "a");
      map.put("2", "b");

      System.out.println(U.toJson(map));

      Map<String, Object> newMap = (Map<String, Object>) U.fromJson($.toJson(map));         
      System.out.println(newMap.get("1")); // -> "a"

    }
}