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

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

 

   

 

 

 

 

posted @ 2018-06-02 20:22  没有名字~  阅读(33459)  评论(0编辑  收藏  举报