zoukankan      html  css  js  c++  java
  • JSONObject 和 JSONArray 的区别和用法

    JSONObject 和 JSONArray 的数据表现形式不同:

    JSONObject的数据是用 {  } 来表示的,例如: { "id" : "1", "name" : "zhuzhu", "age" : "22", "sex" : "男"} 

    JSONArray 是JSONObject组成的数组,是{ }外层套了一个 [ ] ,里边有一个或者多个 { } ,比如  [ {  "id" : "1", "name" : "zhuzhu", "age" : “22", "sex" : "男" } ] 

    总结一下 JSONObject 外层是 { },JSONArray外层是 [ ] 
    大家处理数据的时候一定要看清楚数据格式,分别使用不同的方法来处理数据,否则是会直接转换异常的!

    下边简单来一个JSONObject小例子:

    引入的包有:

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;

    @Test
    public
    void testJSONObject(){ String str ="{id:"1",name:"zhuzhu",age:"22",sex:"男"}"; JSONObject jsonObject = JSONObject.parseObject(str); Integer id = jsonObject.getInteger("id"); String name = jsonObject.getString("name"); String age = jsonObject.getString("age"); String sex = jsonObject.getString("sex"); System.out.println("我是"+name+"我今年"+age+"岁啦,我的性别是"+sex); }

      输出为 :  我是zhuzhu我今年22岁啦,我的性别是男

    再简单来一个JSONArray 的例子:

    @Test
    public
    void testJSONArray(){ String str = "[{"id":"1","name":"zhuzhu","age":"22","sex":"男"}]"; JSONArray jsonArray =JSON.parseArray(str); Integer id = null; String name = null ; String age = null ; String sex = null ; for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); id = jsonObject.getInteger("id"); name = jsonObject.getString("name"); age = jsonObject.getString("age"); sex = jsonObject.getString("sex"); } System.out.println("我是"+name+"我今年"+age+"岁啦,我的性别是"+sex); }

    输出为 :  我是zhuzhu我今年22岁啦,我的性别是男

    好了 这就结束了,希望能帮到大家,这里也有很多不全面的地方,只是给一种简单的参考,如有问题请批评指出 ,谢谢

  • 相关阅读:
    线性回归——梯度下降法
    线性回归——最小二乘法_实例(二)
    线性回归——最小二乘法(二)
    线性回归——最小二乘法_实例(一)
    线性回归——最小二乘法(一)
    Spark——SparkContext简单分析
    Kubernets搭建Kubernetes-dashboard
    Docker中部署Kubernetes
    Akka初步介绍
    laravel The Process class relies on proc_open, which is not available on your PHP installation.
  • 原文地址:https://www.cnblogs.com/kevinZhu/p/9241417.html
Copyright © 2011-2022 走看看