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


当前回答

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

JSONObject jsonObject = JSONObject.fromObject(myMap);

其他回答

以下是我与GSON的单线解决方案:

myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);

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

    }

}

我使用阿里巴巴fastjson,简单明了:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>VERSION_CODE</version>
</dependency>

和导入:

import com.alibaba.fastjson.JSON;

然后:

String text = JSON.toJSONString(obj); // serialize
VO vo = JSON.parseObject("{...}", VO.class); //unserialize

一切都好。

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

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

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);

希望这能有所帮助。

谢谢。