Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to python's json.dumps

Tags:

java

python

json

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?

like image 242
jerrymouse Avatar asked Dec 22 '22 04:12

jerrymouse


1 Answers

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.

like image 153
zengr Avatar answered Dec 24 '22 01:12

zengr