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转化为ArrayListpublic static ArrayList JSONList2Object(String jsonList){ ArrayList objectList=(ArrayList ) 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 objectList=JSONList2Object(listData); for(int i=0;i
注意要导入jar:
<dependency>
<groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.2</version> </dependency>