json详解

大家熟悉的 xml 和 json ,分享一下我关于json的学习。

在android客服端:
1,JSONObject object = new JSONObject();

Creates a new JSONObject with name/value mappings from the JSON string.
Parameters:
        json - a JSON-encoded string containing an 
        object.
Throws:
        JSONException - if the parse fails or doesn't 
        yield a JSONObject.

2,JSONArray personData = object.getJSONArray("personDate");

A dense indexed sequence of values. Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans,
 Integers, Longs, Doubles, null or JSONObject.NULL. Values
 may not be NaNs, infinities, or of any type not listed here.

JSONArray has the same type coercion behavior and optional/mandatory accessors as JSONObject. 
See that class' documentation for details.
大意就是:一个密集的索引序列的值,可以存放各种类型的jsonobjects

getJSONArray:Returns the value mapped by name if it exists and is a JSONArray。

3.personData.getJSONObject(i);

getJSONObject::
Returns the value at index if it exists and is a 
JSONObject.
Throws:
JSONException - if the value doesn't exist or is not a JSONObject.
比如:
JSONObject school = schoolInfos.getJSONObject(j);

String schoolName = school.getString("school_name");
这样就获取的值

客户端:生产json,这儿我们使用的是gson的包,google提供的,由于我是idea开发,所以包来源于 源 。导包直接在网络上获取,如果你是使用的eclipse,那就在网上下载对应的包。本地导入。

<orderEntry type="library" exported="" name="com.google.api-client:google-api-client-gson:1.21.0" level="project" />
处理好类的对应关系,然后直接使用类的对象result。这样就直接可以生产json数据,具体分析在下面的实例代码中体现。
 Gson json = new Gson();
 json.toJson(result);

下面就是实例了:
1,客户端生产json数据:

下面生产的json数据,我是在慕课网学习的,学习网站很多,各异自由选择。


{
    "result": 1,
    "personDate": [
        {
            "name": "nate",
            "age": 12,
            "url": "http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg",
            "schoolInfo": [
                {
                    "school_name": "清华"
                },
                {
                    "school_name": "北大"
                }
            ]
        },
        {
            "name": "nate",
            "age": 12,
            "url": "http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg",
            "schoolInfo": [
                {
                    "school_name": "人大"
                },
                {
                    "school_name": "浙大"
                }
            ]
        }
    ]
}

1,定义一个SchoolInfo类

public class SchoolInfo {
    public String getSchool_name() {
        return school_name;
    }

    public void setSchool_name(String school_name) {
        this.school_name = school_name;
    }

    private String school_name;
}

2,Person类,定义

public class Person {
    private String name;
    private int age;
    private String url;

    private List<SchoolInfo> schoolInfo;

    /////////////////////////////////////////////

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public List<SchoolInfo> getSchoolInfo() {
        return schoolInfo;
    }

    public void setSchoolInfo(List<SchoolInfo> schoolInfo) {
        this.schoolInfo = schoolInfo;
    }
}

3,Result类

 */
public class Result {
    private int result;
    private List<Person> personDate;

    ///////////////////////////////////////////

    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    public List<Person> getPersonDate() {
        return personDate;
    }

    public void setPersonDate(List<Person> personDate) {
        this.personDate = personDate;
    }
}

4,生产json数据代码:

 Result result = new Result();
        result.setResult(1);

        List<Person> list = new ArrayList<Person>();


        Person person1 = new Person();
        person1.setName("nate");
        person1.setAge(12);
        person1.setUrl("http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg");

        List<SchoolInfo> schools = new ArrayList<>();
        SchoolInfo schoolInfo1 = new SchoolInfo();
        schoolInfo1.setSchool_name("清华");
        SchoolInfo schoolInfo2 = new SchoolInfo();
        schoolInfo2.setSchool_name("北大");

        schools.add(schoolInfo1);
        schools.add(schoolInfo2);

        person1.setSchoolInfo(schools);
        list.add(person1);

        ////////////////////////////////////////////
        Person person2 = new Person();
        person2.setName("nate");
        person2.setAge(12);
        person2.setUrl("http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg");

        List<SchoolInfo> schools2 = new ArrayList<>();
        SchoolInfo schoolInfo3 = new SchoolInfo();
        schoolInfo3.setSchool_name("人大");
        SchoolInfo schoolInfo4 = new SchoolInfo();
        schoolInfo4.setSchool_name("浙大");

        schools2.add(schoolInfo3);
        schools2.add(schoolInfo4);



        person2.setSchoolInfo(schools2);
        list.add(person2);

        result.setPersonDate(list);

        Gson json = new Gson();
        System.out.println(json.toJson(result));

这样,生产的代码和上面提供的就完全一样了,具体代码自行分析吧。


手机端,移动段, 解析json数据

String json = getJsonforServer();;//获取的json数据
 JSONObject object = new JSONObject(json);

 List<Person> persons = new ArrayList<Person>();

 int result = object.getInt("result");

if (result == 1) {

 JSONArray personData = object.getJSONArray("personDate");

 for (int i = 0; i < personData.length(); i++) {

         Person personObject = new Person();
          persons.add(personObject);
          JSONObject person = personData.getJSONObject(i);

          String name = person.getString("name");
          int age = person.getInt("age");
          String url = person.getString("url");
           personObject.setName(name);
          personObject.setAge(age);
          personObject.setUrl(url);



          JSONArray schoolInfos = person.getJSONArray("schoolInfo");

          List<SchoolInfo> schInfos = new ArrayList<SchoolInfo>();
                    personObject.setSchoolInfo(schInfos);

               for (int j = 0; j < schoolInfos.length(); j++) {
                  JSONObject school = schoolInfos.getJSONObject(j);
                  String schoolName = school.getString("school_name");
                   System.out.println(schoolName + "=========");

                   SchoolInfo info = new SchoolInfo();
                        info.setSchool_name(schoolName);
                    schInfos.add(info);
                }
              }
         return persons;


以下资料来源于 深入理解android网络编程 书籍

解析 JSON 数据时, 首先需要明确待解析的是 JSON Object 还是 JSON Array, 然后再

解析。 举例如下。

( 1) 解析 JSON Object 之一

下面是一个简单的 JSON Object, name 为名称, Lili 是 name 的值, 将 name 和 Lili 用“:”

隔开, 其文本如下。

{"name":"Lili"}

JSONObject.getString( "String") 方 法 可 以 得 到 JSON 对 象 中 String 名 称 对 应 的 值。

下面是对上面 JSON 对象的解析方法:

// 新建 JSONObject, jsonString 字符串中为上面的 JSON 对象的文本

JSONObject demoJson = new JSONObject(jsonString);

// 获取 name 名称对应的值

String s = demoJson.getString("name");



( 2) 解析 JSON Object 之二

下 面 是 一 个 包 含 两 个“ 名 称 / 值 ” 对 的 JSON 对 象, 两 个“ 名 称 / 值 ” 对 分 别 是

"name1":"android""name2":"iphone", 中间使用“,”隔开, 其文本如下:

{"name1":"android","name2":"iphone"}

上面 JSON 对象的解析方法如下:

// 新建 JSONObject 对象, 将 jsonString 字符串转换为 JSONObject 对象

// jsonString 字符串为上面的文本

JSONObject demoJson = new JSONObject(jsonString);

// 获取名称为 name1 对应的值



String name1= demoJson.getString("name1");

// 获取名称为 name2 对应的值

String name2 = demoJson.getString("name2");



( 3) 解析 JSON Array

下面是一个简单的 JSONArray, number 为数组名称,[ 1,2,3] 为数组的内容, 其 JSON

文本表示如下:

{"number":[1,2,3]}

上面的 JSON Array 解析方法如下:

// 新建 JSONObject 对象, 将 jsonString 字符串转换为 JSONObject 对象

// jsonString 字符串为上面的文本

JSONObject demoJson = new JSONObject(jsonString);

// 获取 number 对应的数组

JSONArray numberList = demoJson.getJSONArray("number");

// 分别获取 numberList 中的每个值

for(int i=0; i<numberList.length(); i++){

// 因为数组中的类型为 int, 所以为 getInt, 其他 getString、 getLong 具有类似的用法

System.out.println(numberList.getInt(i));

} (



4) 解析 JSON ObjectJSON Array 混合对象

下 面 是 一 个 JSON ObjectJSON Array 的 混 合 文 本, mobile 为 JSON Object 名

称, 其对应的值为 JSON ArrayJSON Array 中包含的对象为 JSON Object, 其文本表

示如下:



{"mobile":[{"name":"android"},{"name":"iphone"}]}



上面文本的解析方法如下:

// 新建 JSONObject 对象, 将 jsonString 字符串转换为 JSONObject 对象

// jsonString 字符串为上面的文本

JSONObject demoJson = new JSONObject(jsonString);

// 首先获取名为 mobile 的对象对应的值

// 该值为 JSONArray, 这里创建一个 JSONArray 对象

JSONArray numberList = demoJson.getJSONArray("mobile");

// 依次取出 JSONArray 中的值

for(int i=0; i<numberList.length(); i++){

// 从第 i 个取出 JSONArray 中的值为 JSON Object“名称 / 值”对

// 通过 getString("name") 获取对应的值

System.out.println(numberList.getJSONObject(i).getString("name"));

}

3.3.3 JSON 打包
要 想 在 客 户 端 通 过 JSON 传 送 对 象, 需 要 在 JSON 把 信 息 全 部“ 打 包 ” 之 后 将
JSONObject 转换为 String。 这样 JSON 就会将“打包”的信息按照特定标准的格式进行
“压缩”, 之后在服务端进行解析, 读取通过 JSON 传送来的信息。
Android 提供的 JSON 解析类都在包 org.json 下, 主要有以下几个。
‰‰ JSONObject: 可以看作是一个 JSON 对象, 这是系统中有关 JSON 定义的基本单元,
即前面提到的“名称 / 值”对。
‰‰ JSONStringer : JSON 文本构建类, 这个类可以帮助快速和方便地创建 JSON 文本。
其最大的优点在于可以减少由于格式的错误导致的程序异常, 引用这个类可以自动
严格按照 JSON 语法规则创建 JSON 文本。 每个 JSONStringer 实体只能对应创建一
个 JSON 文本。
‰‰ JSONArray : 它代表一组有序的数值。 将其转换为 String 输出 (toString) 所表现的形
式是用方括号包裹, 数值以逗号“,”分隔, 即前面提到的值的有序列表。
‰‰ JSONTokener: JSON 解析类。
‰‰ JSONException: JSON 中涉及的异常。
下面看一个用 JSONObject、 JSONArray 来构建 JSON 文本的例子, 其需要构建的文本
如下:
{
"Strings" : { "Strings1" : "MyStrings", "Strings2" : "MyStrings" },
"Number" : ["987654321", "123456789","456789123"],
"String" : "good",
"Int" : 100,
"Boolean" : false
}
上面的 JSON 对象中包含了 5 个“名称 / 值”对, 其中名称为 Strings 的对应的值本身
也是一个包含 2 个“名称 / 值”对的 JSON 对象 ; 名称为 Number 的对应的值为一个 JSON
Array ; 名称为 String 的对应的值为一个字符串 ; 名称为 Int 的对应的值为一个整型 ; 名称
为 Boolean 的对应的值为布尔型。
构建上述文本的主要代码如下:
try {
// 创建 JSONObject 对象
JSONObject mJSONObject = new JSONObject();
// 为 Strings 创建 JSONObject 对象
JSONObject Strings = new JSONObject();
// 为 Strings JSONObject 对象添加第一个“名称 / 值”对
Strings.put("Strings1", " MyStrings");
// 为 Strings JSONObject 对象添加第二个“名称 / 值”对

Strings.put("Strings2", " MyStrings");
// 将 Strings 添加到 mJSONObject 中
mJSONObject.put("Strings", Strings);
// 为 Number 创建 JSONArray 对象
JSONArray Number = new JSONArray();
// 将有序列表添加到 Number 中
Number.put("987654321").put("123456789").put("456789123");
// 将 Number 添加到 mJSONObject 中
mJSONObject.put("Number", Number);
// 将 Int“名称 / 值”对添加到 mJSONObject 中
mJSONObject.put("Int", 100);
// 将 Boolean“名称 / 值”对添加到 mJSONObject 中
mJSONObject.put("Boolean", false);
} catch (JSONException ex) {
// 进行异常处理
throw new RuntimeException(ex);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值