java解析json的方法

JSON数据解析的有点在于他的体积小,在网络上传输的时候可以更省流量,所以使用越来越广泛,下面介绍使用JsonObject和JsonArray的两种方式解析Json数据。

使用以上两种方式解析json均需要依赖json-lib.jar开发包使用依赖包

1、JsonObject

使用JsonObject解析只有一条数据的json是非常方便的例如:"{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"}"


  
  
  1. public static void main(String[] args) {
  2. String jsonString = "{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"}";
  3. JSONObject json = JSONObject.fromObject(jsonString);
  4. User user = new User();
  5. user.setName(json.getString( "name"));
  6. user.setPassword(json.getString( "password"));
  7. user.setEmail(json.getString( "email"));
  8. System.out.println(user.toString());
  9. }

2、JsonArray

使用JsonArray解析数组数据的json是非常方便的例如:"[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"},{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"[email protected]\"}]"


  
  
  1. String json = <span style= "color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"> "[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"},</span><span style="color: rgb( 51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px; ">{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"[email protected]\"}</span><span style="color: rgb( 51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px; ">]"</span>;
  2. JSONArray jsonArray = JSONArray.fromObject(json);
  3. ArrayList<User> users = new ArrayList<User>();
  4. for ( int i = 0; i < jsonArray.size(); i++) {
  5. User userM = new User();
  6. user.setName(jsonArray.getJSONObject(i).getString( "name"));
  7. user.setpassword(jsonArray.getJSONObject(i).getString( "password"));
  8. user.setEmail(jsonArray.getJSONObject(i).getString( "email"));
  9. users.add(user);
  10. }
  11. for (User user : users) {
  12. System.out.println(user.toString());
  13. }

通过以上两种方式可以解析不同格式的json数据


转载自:https://blog.csdn.net/chenfengdejuanlian/article/details/52190462

猜你喜欢

转载自blog.csdn.net/qq_32113189/article/details/83858545