jerrymouse jerrymouse - 28 days ago 8
Java Question

Java equivalent to python's json.dumps

Python code:

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
is a valid json produced by
json.dumps
even if unsafe_string contains unicodes. Is there a similar function in Java?

Answer

You need json-simple or Google'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"} 

Similarly Decoding.

Comments