json字符串和object之间的相互转化

时间:2022-03-27 21:21:25
package asi;
import java.util.ArrayList;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
public class TestJSONObject {
private String name;
private String sex; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
} //json字符串转化为JSONObject类
public static JSONObject JSON2Object(String json){
JSONObject object=(JSONObject) JSONObject.parseObject(json);
return object;
}
//json的list转化为ArrayList<JSONObject>
public static ArrayList<JSONObject> JSONList2Object(String jsonList){
ArrayList<JSONObject> objectList=(ArrayList<JSONObject>) JSONObject.parseObject(jsonList,ArrayList.class);
return objectList;
} //object转化为json
public static String Object2JSON(Object o){
return JSON.toJSONString(o); } public static void main(String[] args) { String json="{\"username\": \"Bonnie\",\"listData\": [{\"address\": \"石景山区\",\"street\": \"裕华路\"},{\"address\": \"海淀区\",\"street\": \"中山路\"}]}";
try{
//1、测试json转换成object
JSONObject object=JSON2Object(json);
String username=(String) object.get("username");
System.out.println(username); String listData=String.valueOf(object.get("listData"));
//(String) object.get("listData");
System.out.println(listData); ArrayList<JSONObject> objectList=JSONList2Object(listData);
for(int i=0;i<objectList.size();i++){
System.out.println((String)((JSONObject) (objectList.toArray())[i]).get("address"));
System.out.println((String)((JSONObject) (objectList.toArray())[i]).get("street"));
}
//2、测试object转化成json
TestJSONObject t=new TestJSONObject();
t.setName("Bonnie");
t.setSex("female"); System.out.println(Object2JSON(t));
}catch(JSONException e){
e.printStackTrace();
} }
}

注意要导入jar:

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.2</version>
  </dependency>