码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA代码解析String字符串(json格式的)

时间:2018-06-02 21:28:33      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:字符串   输出   color   email   str   array   zhang   nbsp   hang   

java解析String字符串(json格式)

  需要jar包:json-lib-2.4-jdk15.jar

一、

  String str = "{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"10371443@qq.com\"}";

  此时用JSONObject:

    

1 String str = "{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"10371443@qq.com\"}";
2 JSONObject json = JSONObject.fromObject(str);
3 System.out.println(json.getString("name"));

 

 

 

 

二、

   String jsonString = "[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"10371443@qq.com\"}"

            + ",{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"1435123@qq.com\"}]";

  此时用JSONArray:

 

1 String jsonString = "[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"10371443@qq.com\"}"
2     + ",{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"1435123@qq.com\"}]";
3 JSONArray jsonArray = JSONArray.fromObject(jsonString);
4 for(int i = 0 ;i < jsonArray.size() ; i++){
5     System.out.println("name = "+jsonArray.getJSONObject(i).getString("name"));
6     System.out.println("password = "+jsonArray.getJSONObject(i).getString("password"));
7     System.out.println("email = "+jsonArray.getJSONObject(i).getString("email"));
8 }

 

 

    

两个的输出结果为:

zhangsan
=========================================
name = zhangsan
password = zhangsan123
email = 10371443@qq.com
name = lisi
password = lisi123
email = 1435123@qq.com

 

   

 

 

 

 

JAVA代码解析String字符串(json格式的)

标签:字符串   输出   color   email   str   array   zhang   nbsp   hang   

原文地址:https://www.cnblogs.com/rgever/p/9126444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!