如何在Java中转换或转换哈希图到JSON对象,并再次将JSON对象转换为JSON字符串?


当前回答

对于使用TypeToken的更复杂的映射和列表,Gson是一种方式。getParameterized方法:

我们有一张这样的地图:

Map<Long, List<NewFile>> map;

我们使用上面提到的getParameterized方法来获取类型,如下所示:

Type listOfNewFiles = TypeToken.getParameterized(ArrayList.class, NewFile.class).getType();
Type mapOfList = TypeToken.getParameterized(LinkedHashMap.class, Long.class, listOfNewFiles).getType();

然后使用Gson对象fromJson方法,使用mapflist对象,像这样:

Map<Long, List<NewFile>> map = new Gson().fromJson(fileContent, mapOfList);

上面提到的对象NewFile看起来是这样的:

class NewFile
{
    private long id;
    private String fileName;

    public void setId(final long id)
    {
        this.id = id;
    }

    public void setFileName(final String fileName)
    {
        this.fileName = fileName;
    }
}

反序列化的JSON是这样的:

{ “1”:[ { “id”:12232年, “文件名”:“test.html” }, { “id”:12233年, “文件名”:“file.txt” }, { “id”:12234年, “文件名”:“obj.json” } ], “2”:[ { “id”:122321年, “文件名”:“test2.html” }, { “id”:122332年, “文件名”:“file2.txt” }, { “id”:122343年, “文件名”:“obj2.json” } ] }

其他回答

迟到总比不到好。如果你想要一个序列化的列表,我使用GSON将HashMap列表转换为字符串。

List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");
list.add(hashMap);

String json = new Gson().toJson(list);

这个json产生[{“关键”:“价值”、“关键”:“价值”,“关键”:“价值”}]

使用json的示例

Map<String, Object> data = new HashMap<String, Object>();
    data.put( "name", "Mars" );
    data.put( "age", 32 );
    data.put( "city", "NY" );
    JSONObject json = new JSONObject();
    json.putAll( data );
    System.out.printf( "JSON: %s", json.toString(2) );

输出:

JSON: {
  "age": 32,
  "name": "Mars",
  "city": "NY"
}

你也可以尝试使用谷歌的GSON。谷歌的GSON是将Java对象转换为JSON表示形式的最佳库。

http://code.google.com/p/google-gson/

你可以使用:

new JSONObject(map);

其他函数可以从它的文档中获得 http://stleary.github.io/JSON-java/index.html

这个解决方案适用于复杂的json:

public Object toJSON(Object object) throws JSONException {
    if (object instanceof HashMap) {
        JSONObject json = new JSONObject();
        HashMap map = (HashMap) object;
        for (Object key : map.keySet()) {
            json.put(key.toString(), toJSON(map.get(key)));
        }
        return json;
    } else if (object instanceof Iterable) {
        JSONArray json = new JSONArray();
        for (Object value : ((Iterable) object)) {
            json.put(toJSON(value));
        }
        return json;
    }
    else {
        return object;
    }
}

您可以使用Jackson将Map转换为JSON,如下所示:

Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");

String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Jackson的Maven依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

If you are using `JSONObject` library, you can convert map to `JSON` as follows: JSONObject Library: import org.json.JSONObject; Map<String, Object> map = new HashMap<>(); // Convert a map having list of values. String[] value1 = new String[] { "value11", "value12", "value13" }; String[] value2 = new String[] { "value21", "value22", "value23" }; map.put("key1", value1); map.put("key2", value2); JSONObject json = new JSONObject(map); System.out.println(json); Maven Dependencies for `JSONObject` : <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20140107</version> </dependency> Hope this will help. Happy coding.