如何在Java中转换或转换哈希图到JSON对象,并再次将JSON对象转换为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

如果你正在使用net.sf.json.JSONObject,那么你不会在其中找到JSONObject(map)构造函数。您必须使用公共静态JSONObject fromObject(对象对象)方法。该方法接受JSON格式的字符串、map、dynabean和javabean。

JSONObject jsonObject = JSONObject.fromObject(myMap);

我们使用Gson。

Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String gsonString = gson.toJson(elements,gsonType);

这通常是Json库的工作,你不应该尝试自己做。所有json库都应该实现您所要求的内容,而且您可以做到 在页面底部的json.org上找到Java Json库的列表。

如果你真的不需要HashMap,你可以这样做:

String jsonString = new JSONObject() {{
  put("firstName", user.firstName);
  put("lastName", user.lastName);
}}.toString();

输出:

{
  "firstName": "John",
  "lastName": "Doe"
}