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中是否有类似的功能?
答案 0 :(得分:7)
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);