加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

10分钟掌握XML、JSON及其解析(下)

发布时间:2020-12-16 05:56:46 所属栏目:百科 来源:网络整理
导读:接上文 2.4 如何解析JSON? Android JSON所有相关类,都在org.json包下。 包括JSONObject、JSONArray、JSONStringer、JSONTokener、JSONWriter、JSONException。 1. 常见方法 目前JSON解析有2种方法,分别是get和opt方法,可以使用JSON 那么使用get方法与使

接上文


2.4 如何解析JSON?


Android JSON所有相关类,都在org.json包下。

包括JSONObject、JSONArray、JSONStringer、JSONTokener、JSONWriter、JSONException。


<1>. 常见方法

目前JSON解析有2种方法,分别是get和opt方法,可以使用JSON

那么使用get方法与使用opt方法的区别是?

JsonObject方法,opt与get建议使用opt方法,因为get方法如果其内容为空会直接抛出异常。不过JsonArray.opt(index)会有越界问题需要特别注意。

opt、optBoolean、optDouble、optInt、optLong、optString、optJSONArray、optJSONObject get、getBoolean、getDouble、getInt、getLong、getString、getJSONArray、getJSONObject

<2>. Android中如何创建JSON?

在Android中应该如何创建JSON呢?

下面展示了一个如何创建JSON的例子:


private String createJson() throws JSONException {

JSONObject jsonObject = new JSONObject();

jsonObject.put("intKey",123);

jsonObject.put("doubleKey",10.1);

jsonObject.put("longKey",666666666);

jsonObject.put("stringKey","lalala");

jsonObject.put("booleanKey",true);

JSONArray jsonArray = new JSONArray();

jsonArray.put(0,111);

jsonArray.put("second");

jsonObject.put("arrayKey",jsonArray);

JSONObject innerJsonObject = new JSONObject();

innerJsonObject.put("innerStr","inner");

jsonObject.put("innerObjectKey",innerJsonObject);

Log.e("Json",jsonObject.toString());

return jsonObject.toString();

}

其输出结果如下所示:

{"intKey":123,"doubleKey":10.1,"longKey":666666666,"stringKey":"lalala","booleanKey":true,"arrayKey":[111,"second"],"innerObjectKey":{"innerStr":"inner"}}


<3>. 如何解析JSON?

下面以视频中解析iQiyi的每个视频album数据为例来说明如何解析JSON:

第一步,需要从网络服务器上发起请求,获取到JSON数据:

JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET,url,null,

new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {

try {

MyLog.d(TAG,"response=" + response);

parseiQiyiInterfaceResponse(response);

} catch (Exception e) {

e.printStackTrace();

}

},new Response.ErrorListener() {

public void onErrorResponse(VolleyError error) {

/*

* if (error instanceof NetworkError) { } else if (error

* instanceof ClientError) { } else if (error instanceof

* ServerError) { } else if (error instanceof

* AuthFailureError) { } else if (error instanceof

* ParseError) { } else if (error instanceof

* NoConnectionError) { } else if (error instanceof

* TimeoutError) { }

*/

MyLog.e(TAG,"onErrorResponse,error=" + error);

}) {

public Map<String,String> getHeaders() throws AuthFailureError {

HashMap<String,String> headers = new HashMap<String,String>();

headers.put("t",iQiyiInterface.getEncryptTimestamp());

headers.put("sign",iQiyiInterface.getSign());

return headers;

};

第二步,获取到对应的对应的JSONObject数据:

public void getJsonObjectString(String url) {

mQueue = VideoApplication.getInstance().getRequestQueue();

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET,"response = " + response.toString());

JSONArray jsonArray = null;

JSONObject jsonObject = null;

jsonObject = response.getJSONObject("response");

jsonArray = jsonObject.getJSONObject("result").getJSONArray("album");

} catch (JSONException e) {

if (jsonArray == null) {

return;

mChannelList = VideoUtils.parseVideoJsonArray(jsonArray);

if (isLoading) {

isLoading = false;

if (mIsGrid) {

mChannelGridAdapter.appendChannelVideoInfo(mChannelList);

} else {

mChannelListAdapter.appendChannelVideoInfo(mChannelList);

mChannelGridAdapter.setChannelVideoInfo(mChannelList);

showOppoGrid();

mChannelListAdapter.setChannelVideoInfo(mChannelList);

showOppoList();

});

jsObjRequest.setTag(TAG);

jsObjRequest.setShouldCache(true);

mQueue.add(jsObjRequest);

mQueue.start();

获取到JSON Object之后,就对这个JSONObject进行解析:

private ArrayList<VideoConstant> parseVideoAlbumJsonObject(JSONObject albumJSONObject,ArrayList<Integer> albumIdJSONArrayList) {

MyLog.d(TAG,"parseVideoAlbumJsonObject,length=" + albumJSONObject.length());

if (albumJSONObject.length() < 1) {

return null;

}

ArrayList<VideoConstant> videos = new ArrayList<VideoConstant>();

try {

for (int index = 0; index < albumJSONObject.length(); index++) {

VideoConstant video = new VideoConstant();

JSONObject itemJsonObject;

itemJsonObject = albumJSONObject.getJSONObject(albumIdJSONArrayList.get(index)

.toString());

video.mAlbumId = itemJsonObject.optString(InterfaceParameterName.ID);

video.mAtitle = itemJsonObject.optString(InterfaceParameterName.TITLE);

video.mEpisodeCount = itemJsonObject.optString(InterfaceParameterName.UPDATE_SET);

video.mTvSets = itemJsonObject.optString(InterfaceParameterName.TV_SETS);

video.mDesc = itemJsonObject.optString(InterfaceParameterName.DESCRIPTION);

video.mCid = itemJsonObject.optString(InterfaceParameterName.CATEGORY_ID);

video.mImg = itemJsonObject.optString(InterfaceParameterName.IMG);

video.mHighimg = itemJsonObject

.optString(InterfaceParameterName.HIGH_RESO_PORT_IMG);

video.mHoriImg = itemJsonObject

.optString(InterfaceParameterName.HIGH_RESO_HORI_IMG);

video.mScore = itemJsonObject.optString(InterfaceParameterName.SCORE);

video.mMainActors = itemJsonObject.optString(InterfaceParameterName.MAIN_ACTOR);

video.mCreateTime = itemJsonObject.optString(InterfaceParameterName.CREATE_TIME);

video.mDuration = itemJsonObject.optString(InterfaceParameterName.DURATION);

video.mTag = itemJsonObject.optString(InterfaceParameterName.TAG);

+ video.mHighimg + ",tvsets=" + video.mTvSets);

videos.add(video);

} catch (JSONException e) {

e.printStackTrace();

return videos;

}

<4>. Android JSON解析库

上面介绍都是使用Android提供的原生类解析JSON,最大的好处是项目不需要引入第三方库,但是如果比较注重开发效率而且不在意应用大小增加几百K的话,有以下JSON可供选择:


  1. Jackson

  2. google-gson

  3. Json-lib

大家可以去对应的官网下载并学习


三、 JSON vs. XML

JSON和XML就像武林界的屠龙刀和倚天剑,那么他们孰强孰弱?

XML长期执数据传输界之牛耳,而JSON作为后起之秀,已经盟主发起了挑战。

那就让他们来进行PK一下:

<1>. JSON相比XML的不同之处


  • 没有结束标签

  • 更短

  • 读写的速度更快

  • 能够使用内建的 JavaScript eval() 方法进行解析

  • 使用数组

  • 不使用保留字

总之: JSON 比 XML 更小、更快,更易解析。

<2>. XML和JSON的区别:

XML的主要组成成分:

XML是element、attribute和element content。

JSON的主要组成成分:

JSON是object、array、string、number、boolean(true/false)和null。

XML要表示一个object(指name-value pair的集合),最初可能会使用element作为object,每个key-value pair 用 attribute 表示:

<student name="John" age="10"/>

但如个某个 value 也是 object,那么就不可以当作attribute:

<student name="John" age="10">

<address>

<country>China</country>

<province>Guang Dong</province>

<city>...</city>

<district>...</district>

...

</address>

</student>

那么,什么时候用element,什么时候用attribute,就已经是一个问题了。

而JSON因为有object这种类型,可以自然地映射,不需考虑上述的问题,自然地得到以下的格式。

{

"name": "John",136)">"age" : 10,136)">"address" : {

"country" : "China",136)">"province" : "Guang Dong",136)">"city" : "..",136)">"district" : "..",136)">}


One More Thing…

XML需要选择怎么处理element content的换行,而JSON string则不须作这个选择。

XML只有文字,没有预设的数字格式,而JSON则有明确的number格式,这样在locale上也安全。

XML映射数组没大问题,就是数组元素tag比较重复冗余。JSON 比较易读。

JSON的true/false/null也能容易统一至一般编程语言的对应语义。

XML文档可以附上DTD、Schema,还有一堆的诸如XPath之类规范,使用自定义XML元素或属性,能很方便地给数据附加各种约束条件和关联额外信息,从数据表达能力上看,XML强于Json,但是很多场景并不需要这么复杂的重量级的东西,轻便灵活的Json就显得很受欢迎了。

打个比方,如果完成某件事有两种方式:一种简单的,一个复杂的。你选哪个?

我只想杀只鸡罢了,用得着牛刀?

JSON与XML相比就是这样的。

四、总结

这篇文章只是对XML和JSON这2种目前主流使用的数据格式进行了解释,并系统的学习了其中的语法及如何进行解析,同时在最好针对XML和JSON做了对比,了解其不同点和各自的优势。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读