android Json详解

Json:一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org

官网地址:http://www.json.org/

JSON Vs XML

1.JSON和XML的数据可读性基本相同

2.JSON和XML同样拥有丰富的解析手段

3.JSON相对于XML来讲,数据的体积小

4.JSON与JavaScript的交互更加方便

5.JSON对数据的描述性比XML较差

6.JSON的速度要远远快于XML

一、JSON语法

 

  JSON 语法规则

 

  • 数据在名称/值对中
  • 数据由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

 

JSON 名称/值对

   JSON 数据的书写格式是:名称/值对。

   名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值:

  "firstName" : "John"

 JSON 值

  JSON 值可以是:

  • 数字(整数或浮点数)
  • 字符串(在双引号中)
  • 逻辑值(true 或 false)
  • 数组(在方括号中)
  • 对象(在花括号中)
  • null
  • JSONObject
  • JSONArray

JSON 对象

JSON 对象在花括号中书写:

对象可以包含多个名称/值对:

{ "firstName":"John" , "lastName":"Doe" }
一个{}就是一个JSONObject

JSON 数组

JSON 数组在方括号中书写:

数组可包含多个对象:

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

在上面的例子中,对象 "employees" 是包含三个对象的数组。每个对象代表一条关于某人(有姓和名)的记录。

二、android提供的json解析类 

android的json解析部分都在包org.json下,主要有以下几个类: 

JSONObject:可以看作是一个json对象,这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External:   应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的Key和Value被冒号":"分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之间是以逗号","分隔。Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULLobject 。

JSONStringer:json文本构建类 ,根据官方的解释,这个类可以帮助快速和便捷的创建JSON text。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

JSONArray:它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:     [value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,     get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONTokener:json解析类 
JSONException:json中用到的异常 

1.JSONObject,JSONArray解析,创建Json

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* 
     json:{ 
     "languages":[ 
     {"id":1,"ide":"Eclispe","name":"java"}, 
     {"id":2,"ide":"Xcode","name":"Swift"}, 
     {"id":3,"ide":"Visual Studio","name":"C++"}], 
     "cat":{"cat":"miao"} 
     
*/  
    public void creatJson2(){  
           
        try {  
            JSONObject root = new JSONObject();  
            JSONObject cat = new JSONObject();  
            cat.put("cat""miao");  
            JSONArray array = new JSONArray();  
               
            JSONObject lan1 = new JSONObject();  
            lan1.put("id"1).put("ide""Eclispe").put("name""java");  
               
            JSONObject lan2 = new JSONObject();  
            lan2.put("id"2).put("ide""Xcode").put("name""Swift");  
            JSONObject lan3 = new JSONObject();  
            lan3.put("id"3).put("ide""Visual Studio").put("name""C++");  
            array.put(lan1);  
            array.put(lan2);  
            array.put(lan3);  
               
            root.put("languages", array);  
            root.put("cat", cat);  
               
            System.out.println("json:"+root.toString());  
               
        catch (JSONException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }

  然后是解析的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public void parseJson(){  
        try {  
            InputStreamReader is = new InputStreamReader(getAssets().open("test2.json"), "UTF-8");  
            BufferedReader br = new BufferedReader(is);  
            String line;  
            StringBuilder builder = new StringBuilder();  
            while((line=br.readLine())!=null){  
                builder.append(line);  
            }  
            is.close();br.close();  
         JSONObject root = new JSONObject(builder.toString());  
         System.out.println("cat:"+root.getString("cat"));  
         JSONArray array = root.getJSONArray("languages");  
         for(int i=0;i<array.length();i++){  
             JSONObject lan = array.getJSONObject(i);  
             System.out.println("..........");  
             System.out.println("id="+lan.getInt("id"));  
             System.out.println("ide="+lan.getString("ide"));  
             System.out.println("name="+lan.getString("name"));  
         }  
            
        catch (UnsupportedEncodingException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }catch (JSONException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }

   这时解析的源文件:

1
2
3
4
5
6
7
8
   "languages":[ 
   {"id":1,"ide":"Eclipse","name":"java"}, 
   {"id":2,"ide":"Xcode","name":"Swift"}, 
   {"id":3,"ide":"Visual Studio","name":"C++"
   ], 
   "cat":"miao" 

  

2.JSONStringer生成json 

Stringers only encode well-formed JSON strings. In particular:

  • The stringer must have exactly one top-level array or object.
  • Lexical scopes must be balanced: every call to array() must have a matching call to endArray() and every call to object() must have a matching call to endObject().  //每次调用array(),必须匹配endArray,object,endObject同理。
  • Arrays may not contain keys (property names).
  • Objects must alternate keys (property names) and values.
  • Values are inserted with either literal value calls, or by nesting arrays or objects.

它定义的所有方法:

它定义的所有方法:
Public Constructors
 JSONStringer()
Public Methods
 JSONStringer array()
Begins encoding a new array.
 JSONStringer endArray()
Ends encoding the current array.
 JSONStringer endObject()
Ends encoding the current object.
 JSONStringer key(String name)
Encodes the key (property name) to this stringer.
 JSONStringer object()
Begins encoding a new object.
 String toString()
Returns the encoded JSON string.
 JSONStringer value(double value)
Encodes value to this stringer.
 JSONStringer value(Object value)
Encodes value.
 JSONStringer value(long value)
Encodes value to this stringer.
 JSONStringer value(boolean value)
Encodes value to this stringer.
它的方法不多,很精简,所以说用Stringer创建json还是很简单的。
 示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*json:{ 
         "languages":[ 
         {"id":1,"ide":"Eclispe","name":"java"}, 
         {"id":2,"ide":"Xcode","name":"Swift"}, 
         {"id":3,"ide":"Visual Studio","name":"C++"}], 
         "cat":{"name":"miao"} 
         }*/  
    public String createJson(){  
        JSONStringer stringer = new JSONStringer();  
        //every call to array() must have a matching call to endArray() and  
        //every call to object() must have a matching call to endObject().  
        try {  
            stringer.object();  
            stringer.key("languages");  
            stringer.array();  
            //数组中的三个对象  
            stringer.object();  
            stringer.key("id").value(1).key("ide").value("Eclispe").key("name").value("java");  
            stringer.endObject();  
               
            stringer.object();  
            stringer.key("id").value(2).key("ide").value("Xcode").key("name").value("Swift");  
            stringer.endObject();  
               
            stringer.object();  
            stringer.key("id").value(3).key("ide").value("Visual Studio").key("name").value("C++");  
            stringer.endObject();  
            stringer.endArray();//数组结束  
               
            stringer.key("cat");  
            stringer.object();  
            stringer.key("name").value("miao").endObject(); //结束object  
               
            stringer.endObject();  
               
            System.out.println("json:"+stringer.toString());  
               
        catch (JSONException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return stringer.toString();  
    }

  Json数据的解析与生成还是很简单的,可以多去官网看看,多看看文档。。。android总结任重道远啊,写博文就是动力啊,坚持坚持。。。。。 

另附一篇很好的博文,介绍了很多方法:http://www.open-open.com/lib/view/open1326376799874.html

转载于:https://www.cnblogs.com/Free-Thinker/p/9708197.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388400.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

react实践

React 最佳实践一、 React 与 AJAXReact 只负责处理 View 这一层&#xff0c;它本身不涉及网络请求 /AJAX: 第一&#xff0c;用什么技术从服务端获取数据&#xff1b; 第二&#xff0c;获取到的数据应该放在 react 组件的什么位置。 事实上是有很多的&#xff1a;fetch()、fetc…

什么样的代码是好代码_什么是好代码?

什么样的代码是好代码编码最佳实践 (Coding Best-Practices) In the following section, I will introduce the topic at hand, giving you a sense of what this post will cover, and how each argument therein will be approached. Hopefully, this will help you decide w…

nginx比较apache

话说nginx在大压力的环境中比apache的表现要好&#xff0c;于是下载了一个来折腾一下。 下载并编译安装&#xff0c;我的编译过程有点特别&#xff1a; 1。去除调试信息&#xff0c;修改$nginx_setup_path/auto/cc/gcc这个文件&#xff0c;将 CFLAGS"$CFLAGS -g" …

计算机主板各模块复位,电脑主板复位电路工作原理分析

电源、时钟、复位是主板能正常工作的三大要素。主板在电源、时钟都正常后&#xff0c;复位系统发出复位信号&#xff0c;主板各个部件在收到复位信号后&#xff0c;同步进入初始化状态。如图7-11所示为复位电路的工作原理图&#xff0c;各个十板实现复位的电路不尽相同&#xf…

Docker制作dotnet core控制台程序镜像

(1)首先我们到某个目录下&#xff0c;然后在此目录下打开visual studio code. 2.编辑docker file文件如下: 3.使用dotnet new console创建控制台程序; 4.使用docker build -t daniel/console:dev .来进行打包; 5.启动并运行镜像; 6.我们可以看到打包完的镜像将近2G,因为我们使用…

【362】python 正则表达式

参考&#xff1a;正则表达式 - 廖雪峰 参考&#xff1a;Python3 正则表达式 - 菜鸟教程 参考&#xff1a;正则表达式 - 教程 re.match 尝试从字符串的起始位置匹配一个模式&#xff0c;如果不是起始位置匹配成功的话&#xff0c;match()就返回none。 re.search 扫描整个字符串并…

在Python中使用Twitter Rest API批量搜索和下载推文

数据挖掘 &#xff0c; 编程 (Data Mining, Programming) Getting Twitter data获取Twitter数据 Let’s use the Tweepy package in python instead of handling the Twitter API directly. The two things we will do with the package are, authorize ourselves to use the …

第一套数字电子计算机,计算机试题第一套

《计算机试题第一套》由会员分享&#xff0c;可在线阅读&#xff0c;更多相关《计算机试题第一套(5页珍藏版)》请在人人文库网上搜索。1、计算机试题第一套1、计算机之所以能自动运算,就是由于采用了工作原理。A、布尔逻辑。B 储存程序。C、数字电路。D,集成电路答案选B2、“长…

Windows7 + Nginx + Memcached + Tomcat 集群 session 共享

一&#xff0c;环境说明 操作系统是Windows7家庭版&#xff08;有点不专业哦&#xff0c;呵呵&#xff01;&#xff09;&#xff0c;JDK是1.6的版本&#xff0c; Tomcat是apache-tomcat-6.0.35-windows-x86&#xff0c;下载链接&#xff1a;http://tomcat.apache.org/ Nginx…

git 版本控制(一)

新建代码库repository 1、在当前目录新建一个git代码库 git init git init projectname 2、下载一个项目&#xff0c;如果已经有了远端的代码&#xff0c;则可以使用clone下载 git clone url 增加/删除/改名文件 1、添加指定文件到暂存区 git add filename 2、添加指定目录到暂…

rollup学习小记

周末在家重构网关的Npm包&#xff0c;用到了rollup&#xff0c;记下笔记 rollup适合库library的开发&#xff0c;而webpack适合应用程序的开发。 rollup也支持tree-shaking&#xff0c;自带的功能。 package.json 也具有 module 字段&#xff0c;像 Rollup 和 webpack 2 这样的…

大数据 vr csdn_VR中的数据可视化如何革命化科学

大数据 vr csdnAstronomy has become a big data discipline, and the ever growing databases in modern astronomy pose many new challenges for analysts. Scientists are more frequently turning to artificial intelligence and machine learning algorithms to analyze…

object-c 日志

printf和NSlog区别 NSLog会自动加上换行符&#xff0c;不需要自己添加换行符&#xff0c;NSLog会加上时间和进程信息&#xff0c;而printf仅将输入的内容输出不会添加任何额外的东西。两者的输入类型也是有区别的NSLog期待NSString*&#xff0c;而printf期待const char *。最本…

计算机真正管理的文件名是什么,计算机题,请大家多多帮忙,谢谢

4、在资源管理器中&#xff0c;若想显示文件名、文件大小和文件类型&#xff0c;应采用什么显示方式。( )A、小图标显示 B、列表显示 C、详细资料显示 D、缩略图显示5、在EXCEL中&#xff0c;可以依据不同要求来提取和汇总数据&#xff0c;4、在资源管理器中&#xff0c;若想显…

小a的排列

链接&#xff1a;https://ac.nowcoder.com/acm/contest/317/G来源&#xff1a;牛客网小a有一个长度为nn的排列。定义一段区间是"萌"的&#xff0c;当且仅当把区间中各个数排序后相邻元素的差为11 现在他想知道包含数x,yx,y的长度最小的"萌"区间的左右端点 …

Xcode做简易计算器

1.创建一个新项目&#xff0c;选择“View-based Application”。输入名字“Cal”&#xff0c;这时会有如下界面。 2.选择Resources->CalViewController.xib并双击&#xff0c;便打开了资源编辑对话框。 3.我们会看到几个窗口。其中有一个上面写着Library&#xff0c;这里…

计算机 编程 教程 pdf,计算机专业教程-第3章编程接口介绍.pdf

下载第3章 编程接口介绍• DB2 UDB应用程序概述• 嵌入S Q L编程• CLI/ODBC应用程序• JAVA应用程序• DAO 、R D O 、A D O应用程序本章将介绍对DB2 UDB 可用的编程方法及其特色&#xff0c;其中一些方法附有简单的例子&#xff0c;在这些例子中&#xff0c;有些并不是只适用…

导入数据库怎么导入_导入必要的库

导入数据库怎么导入重点 (Top highlight)With the increasing popularity of machine learning, many traders are looking for ways in which they can “teach” a computer to trade for them. This process is called algorithmic trading (sometimes called algo-trading)…

windows查看系统版本号

windows查看系统版本号 winR,输入cmd&#xff0c;确定&#xff0c;打开命令窗口&#xff0c;输入msinfo32&#xff0c;注意要在英文状态下输入&#xff0c;回车。然后在弹出的窗口中就可以看到系统的具体版本号了。 winR,输入cmd&#xff0c;确定&#xff0c;打开命令窗口&…

02:Kubernetes集群部署——平台环境规划

1、官方提供的三种部署方式&#xff1a; minikube&#xff1a; Minikube是一个工具&#xff0c;可以在本地快速运行一个单点的Kubernetes&#xff0c;仅用于尝试Kubernetes或日常开发的用户使用。部署地址&#xff1a;https://kubernetes.io/docs/setup/minikube/kubeadm Kubea…