Java相当于python的json.dumps

时间:2011-12-15 05:29:40

标签: java python json

Python代码:

import json
jsonvalue = json.dumps({"key":key_string,"value":unsafe_string})

cursor_mysql.execute("""UPDATE data SET json = %s WHERE id = %s""", (jsonvalue, somerowid)) 

jsonvalue是由json.dumps生成的有效json,即使unsafe_string包含unicodes也是如此。 Java中是否有类似的功能?

3 个答案:

答案 0 :(得分:7)

您需要json-simpleGoogle's gson

Encoding using json-simple

  JSONObject obj=new JSONObject();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  System.out.print(obj);


Result: {"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"} 

同样Decoding

答案 1 :(得分:2)

使用Jackson

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(dst, obj); // where 'dst' can be File, OutputStream or Writer

答案 2 :(得分:1)

使用flexjson

String json = new flexjson.JSONSerializer().serialize(obj);