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


当前回答

我找到了另一种处理方法。

Map obj=new HashMap();    
obj.put("name","sonoo");    
obj.put("age",new Integer(27));    
obj.put("salary",new Double(600000));   
String jsonText = JSONValue.toJSONString(obj);  
System.out.print(jsonText);

希望这能有所帮助。

谢谢。

其他回答

你可以使用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));       

    }

}

就我而言,我不想要任何依赖。使用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(", "))+"}";

使用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/

对于使用org.json.simple的用户。JSONObject,你可以将映射转换为Json String并解析它来获得JSONObject。

JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));

如果您正在使用JSR 374:用于JSON处理的Java API (javax JSON) 这似乎很管用:

    JsonObjectBuilder job = Json.createObjectBuilder((Map<String, Object>) obj);
    JsonObject jsonObject = job.build();