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

Posted 小毛喵喵

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA代码解析String字符串(json格式的)相关的知识,希望对你有一定的参考价值。

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

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

一、

  String str = "{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"}";

  此时用JSONObject:

    

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

 

 

 

 

二、

   String jsonString = "[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"}"

            + ",{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"[email protected]\"}]";

  此时用JSONArray:

 

1 String jsonString = "[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"}"
2     + ",{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"[email protected]\"}]";
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 = [email protected]

 

   

 

 

 

 

以上是关于JAVA代码解析String字符串(json格式的)的主要内容,如果未能解决你的问题,请参考以下文章

java校验json格式及内容

java 解析json字符串

java获取json格式中的值

java包路径解析成json

Java入门系列:处理Json格式数据

JAVA对象转换成JSON字符串与JAVA String有啥区别