json

来源:互联网 发布:如何查看tcp端口 编辑:程序博客网 时间:2024/06/13 05:37




public static void main(String[] args) throws Exception {
   
    String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ;  // 一个未转化的字符串

    JSONArray json = JSONArray.fromObject(str ); // 首先把字符串转成 JSONArray  对象

    if(json.size()>0){


      for(int i=0;i<json.size();i++){


        JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组,把每一个对象转成 json 对象


        System.out.println(job.get("name")+"="+job.get("value")) ;  // 得到 每个对象中的属性值
      }
    }
}

执行结果:
a=aa
b=bb
c=cc
d=dd


jeson遍历数组:

     String str="[{likes:['JavaScript','Skiing','Apple Pie']}]";

    JSONArray json = JSONArray.fromObject(str ); // 首先把字符串转成 JSONArray  对象

    if(json.size()>0){
      for(int i=0;i<json.size();i++){
        JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组,把每一个对象转成 json 对象
        System.out.println(job.get("likes")) ;  // 得到 每个对象中的属性值
        JSONArray json1 = JSONArray.fromObject(job.get("likes") );
        System.out.println(json1.size());
        for (Object object : json1) {
            System.out.println(object);
        }
      }
    }

执行结果:

["JavaScript","Skiing","Apple Pie"]
3
JavaScript
Skiing
Apple Pie


第3种
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

     String str="[{likes:['JavaScript','Skiing','Apple Pie']}]";

   JSONArray json = JSONArray.fromObject(str ); // 首先把字符串转成 JSONArray  对象

    if(json.size()>0){
      for(int i=0;i<json.size();i++){
        JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组,把每一个对象转成 json 对象
        System.out.println(job.get("likes")) ;  // 得到 每个对象中的属性值
        JSONArray json1 = JSONArray.fromObject(job.get("likes") );
        System.out.println(json1.size());
        for (Object object : json1) {
            System.out.println(object);
        }
      }
    }
执行结果:
["JavaScript","Skiing","Apple Pie"]
3
JavaScript
Skiing
Apple Pie






原创粉丝点击