1、所需jar包
需要导入json的jar包和json所依赖的jar包至builtPath路径下
json-lib-2.4-jdk15.jar
commons-beanutils-1.8.0.jar
commons-collections-3.2.1-1.0.0.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
2、import
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
3、使用JsonObject解析只有一条数据的json
public static void main(String[] args) {
String jsonString="{\"name\":\"zhangsan\",\"password\":
\"zhangsan123\",\"email\":\"10371443@qq.com\"}";
JSONObject json =JSONObject.fromObject(jsonString);
User user = new User();
user.setName(json.getString("name"));
user.setPassword(json.getString("password"));
user.setEmail(json.getString("email"));
}
备注,在json.cn中打开jsonString如下:
{
"name":"zhangsan",
"password":"zhangsan123",
"email":"10371443@qq.com"
}
4、使用JsonArray解析数组数据的json
String json = "{\"personData\":[
{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"10371443@qq.com\"},
{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"1435123@qq.com\"}]
}";
JSONArray jsonArray = JSONArray.fromObject(json);
for(int i = 0; i < jsonArray.size(); i++) {
User user = new User();
user.setName(jsonArray.getJSONObject(i).getString("name"));
user.setpassword(jsonArray.getJSONObject(i).getString("password"));
user.setEmail(jsonArray.getJSONObject(i).getString("email"));
users.add(user);
}
备注,在json.cn中打开jsonString如下:
{
"personData":[
{
"name":"zhangsan",
"password":"zhangsan123",
"email":10371443@qq.com
},
{
"name":"lisi",
"password":"lisi123",
"email":1435123@qq.com
}
]
}