Conversion between java object, json objects, json string

1. simple analytical json string

First json json string into the object, and then parse json objects, as follows.

JSONObject jsonObject = JSONObject.fromObject(jsonStr);

  Its value obtained in accordance with the key json

String name = jsonObject.getString("name");
int num = jsonObject.getInt("num");
String sex = jsonObject.getString("sex");
int age = jsonObject.getInt("age");

 

2. The json string into java objects

Similarly json first string into json objects, and then convert the object into json java object, as shown below.

JSONObject obj = new JSONObject () fromObject (jsonStr);. // json string into the target json

The json object into a java object

Person jb = (Person) JSONObject.toBean (obj, Person.class); // built json object into Person object

 

3. The java object is converted to json string

Json java object into first object, json object into a string json

JSONObject json = JSONObject.fromObject (obj); // java object to convert the object json

String str = json.toString (); // the object into a string json

 

Guess you like

Origin www.cnblogs.com/txf0324/p/11041029.html