如何在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/

其他回答

就我而言,我不想要任何依赖。使用Java 8,你可以得到一个JSON字符串,如下所示:

Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
String json = "{"+map.entrySet().stream()
    .map(e -> "\""+ e.getKey() + "\":\"" + String.valueOf(e.getValue()) + "\"")
    .collect(Collectors.joining(", "))+"}";

Gson还可以用于序列化任意复杂的对象。

下面是如何使用它:

Gson gson = new Gson(); 
String json = gson.toJson(myObject); 

Gson将自动将集合转换为JSON数组。Gson可以序列化私有字段并自动忽略瞬态字段。

    import org.json.JSONObject;

    HashMap<Object, Object> map = new HashMap<>();
    String[] list={"Grader","Participant"};
    String[] list1={"Assistant","intern"};
    map.put("TeachingAssistant",list);
    map.put("Writer",list1);
    JSONObject jsonObject = new JSONObject(map);
    System.out.printf(jsonObject.toString());

    // Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}

你可以使用XStream——它真的很方便。请看这里的例子

package com.thoughtworks.xstream.json.test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class WriteTest {

    public static void main(String[] args) {

      HashMap<String,String> map = new HashMap<String,String>();
      map.add("1", "a");
      map.add("2", "b");
      XStream xstream = new XStream(new JettisonMappedXmlDriver());

      System.out.println(xstream.toXML(map));       

    }

}

如果你需要在代码中使用它。

Gson gsone = new Gson();
JsonObject res = gsone.toJsonTree(sqlParams).getAsJsonObject();