身为新手,在运用网络解析json数据的时候,发现先会用Gson等框架解析json,然后就懒起来学原生解析了,这下在看别人写的demo的时候就尴尬了,一块块的,不懂写什么,气氛十分尴尬。

不多说,先来条好bolg的链接:http://blog.csdn.net/android_lyp/article/details/52072822

JSON对数据的描述形式,既然是形式,那么它的数据形式是什么样的:

    • 对象的描述是: {}
    • 数组的描述是: []
    • 属性或值的描述是: “”
    • 连接之间的描述是: :
  • 手动创建javaBean对象的看JSON数据,请记住:拿到一些JSON数据,首先看符号, 有个原则,从外到内看,看到{}这个是个对象,就创建对象,看到[]就创建数据,
  • 但是这里有个问题,看![{},{}],这个看,1. 创建一个List容器 2. 再看里面,{}就创建对象,说明这个容器的泛型就是这个对象

原生解析个人不推荐用,因为加载数据的性能比较低,如果写的界面适配器写的不好等因素加起来的话,加载数据就很慢很慢,现在有很多热门的库类例如Gson等等

Activity中的网络解析(因为没用框架,所以代码会臃肿但是方便开发 ,不利于后面维护)

(1)原生解析---》getJsonObject

package com.tfot.hotel.yichengyiyu.Activity.zhou_activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView; import com.squareup.okhttp.Call;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.tfot.hotel.yichengyiyu.Activity.NewActivivty.XiangQingActivity;
import com.tfot.hotel.yichengyiyu.Activity.NewActivivty.XiangQingActivity_Long;
import com.tfot.hotel.yichengyiyu.Activity.zhou_activity.adapter.ChaXunJieGuoAdapter;
import com.tfot.hotel.yichengyiyu.Activity.zhou_activity.bean.ChaXunJieGuo;
import com.tfot.hotel.yichengyiyu.R;
import com.tfot.hotel.yichengyiyu.Util.Common;
import com.tfot.hotel.yichengyiyu.Util.base.BaseActivity; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription; /**
* 查询结果界面
* Created by huizhou on 2017/6/26.
*/ public class ChaXunJieGuoActivity extends BaseActivity {
private List<ChaXunJieGuo> chaXunJieGuoList=new ArrayList<>(); //查询结果数据源
private String changOrduang ;// CONDITION 判断长租或者短租的字符串
private Boolean yeOrNo = false ;//查询内容是否存在
private String sousuoneiron;
private ListView activity_chaxunjieguo_list;
private ImageView activivty_chaxunjieguo_fanhuui;
private ChaXunJieGuoAdapter chaXunJieGuoAdapter;
private View kongbaiye_sousuo; private CompositeSubscription mCompositeSubscription;//第三方线程
private final OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chaxunjieguo_l);
Intent intent = getIntent();
Bundle bundle=intent.getExtras();//.getExtras()得到intent所附带的额外数据
changOrduang = bundle.getString("changOrduang");
sousuoneiron = bundle.getString("sousuojieguoneiron");
initData(); } private void initData() { mCompositeSubscription = new CompositeSubscription(); //第三方线程 activity_chaxunjieguo_list = (ListView) findViewById(R.id.activity_chaxunjieguo_list);
activivty_chaxunjieguo_fanhuui = (ImageView) findViewById(R.id.activivty_chaxunjieguo_fanhuui); kongbaiye_sousuo = findViewById(R.id.kongbaiye_sousuo); //空白页 chaxunjieguo(sousuoneiron);
chaXunJieGuoAdapter = new ChaXunJieGuoAdapter(ChaXunJieGuoActivity.this,chaXunJieGuoList);
activity_chaxunjieguo_list.setAdapter(chaXunJieGuoAdapter); activity_chaxunjieguo_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO 查询条目跳转
Intent intent =null;
if(changOrduang.equals("day")){
intent = new Intent(ChaXunJieGuoActivity.this, XiangQingActivity.class); //短租的房间详情页
}else if(changOrduang.equals("long")){
intent = new Intent(ChaXunJieGuoActivity.this, XiangQingActivity_Long.class); //长租的房间详情页
}
Bundle bundle = new Bundle();
bundle.putString("RoomStyleId",chaXunJieGuoList.get(position).getRoomStyleId());
bundle.putString("Brandname",chaXunJieGuoList.get(position).getBrandname());
intent.putExtras(bundle);
startActivity(intent); }
}); activivty_chaxunjieguo_fanhuui.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
}); } //查询结果的的网路连接
private void chaxunjieguo(final String chaxuneironB){
Subscription subscription = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
RequestBody formBody = new FormEncodingBuilder()
.add("ACT", "likesearch")
.add("CONDITION",changOrduang)
.add("content",chaxuneironB)
.build(); final Request request = new Request.Builder()
.url(Common.NEW_CHAXUNJIEGUO)
.post(formBody)
.build(); Call call = client.newCall(request);
try {
Response response = call.execute();
subscriber.onNext(response.body().string());
subscriber.onCompleted();
} catch (IOException e) {
e.printStackTrace();
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
//原生解析
try {
JSONArray array = new JSONArray(s);
chaXunJieGuoList.clear();
for (int i = 0; i < array.length(); i++) {
JSONObject temp = (JSONObject) array.get(i);
String RoomStyleId=temp.getString("RoomStyleId");
String Unitprice=temp.getString("Unitprice");
String evaluate=temp.getString("evaluate");
JSONObject banner=temp.getJSONObject("Brand"); String Brandname=banner.getString("Brandname"); JSONArray jsonArray=temp.getJSONArray("RoomStyleImage");
ArrayList<String> RoomStyleImage=new ArrayList<String>();
for (int i2=0;i2<jsonArray.length();i2++){
String a= Common.BASIC_IC_API+jsonArray.get(i).toString();
RoomStyleImage.add(a);
}
String RoomStyleAddres=temp.getString("RoomStyleAddres");
String Roomlongrentom=temp.getString("Roomlongrentom");
String RoomStyleName = temp.getString("RoomStyleName");
String RoomStar = temp.getString("RoomStar");
ChaXunJieGuo chaXunJieGuoData = new ChaXunJieGuo(RoomStyleId,Unitprice,
evaluate, Brandname,RoomStyleImage,RoomStyleAddres,Roomlongrentom,RoomStyleName,RoomStar);
chaXunJieGuoList.add(chaXunJieGuoData);
}
if(!chaXunJieGuoList.isEmpty()){
kongbaiye_sousuo.setVisibility(View.GONE);
activity_chaxunjieguo_list.setVisibility(View.VISIBLE);
}else{
kongbaiye_sousuo.setVisibility(View.VISIBLE);
activity_chaxunjieguo_list.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
chaXunJieGuoAdapter.notifyDataSetChanged();
}
});
mCompositeSubscription.add(subscription);
}
}

bean

package com.tfot.hotel.yichengyiyu.Activity.zhou_activity.bean;

import java.io.Serializable;
import java.util.ArrayList; /**
* Created by huizhou on 2017/6/26.
*/ public class ChaXunJieGuo implements Serializable {
private String RoomStyleId;
private String Unitprice;
private String evaluate;
private String Brandname;
private ArrayList<String> RoomStyleImage;
private String RoomStyleAddres;
private String Roomlongrentom;
private String RoomStyleName;
private String RoomStar; public String getRoomStyleName() {
return RoomStyleName;
} public void setRoomStyleName(String roomStyleName) {
RoomStyleName = roomStyleName;
} public ChaXunJieGuo(String roomStyleId, String unitprice, String evaluate, String brandname,ArrayList<String> roomStyleImage, String roomStyleAddres, String roomlongrentom,String roomStyleName,String roomStar) {
RoomStyleId = roomStyleId;
Unitprice = unitprice;
this.evaluate = evaluate;
Brandname = brandname;
RoomStyleImage = roomStyleImage;
RoomStyleAddres = roomStyleAddres;
Roomlongrentom = roomlongrentom;
RoomStyleName = roomStyleName;
RoomStar = roomStar;
} public String getRoomStar() {
return RoomStar;
} public void setRoomStar(String roomStar) {
RoomStar = roomStar;
} public String getRoomStyleId() {
return RoomStyleId;
} public void setRoomStyleId(String roomStyleId) {
RoomStyleId = roomStyleId;
} public String getUnitprice() {
return Unitprice;
} public void setUnitprice(String unitprice) {
Unitprice = unitprice;
} public String getEvaluate() {
return evaluate;
} public void setEvaluate(String evaluate) {
this.evaluate = evaluate;
} public String getBrandname() {
return Brandname;
} public void setBrandname(String brandname) {
Brandname = brandname;
} public ArrayList<String> getRoomStyleImage() {
return RoomStyleImage;
} public void setRoomStyleImage(ArrayList<String> brandbigimage) {
RoomStyleImage = brandbigimage;
} public String getRoomStyleAddres() {
return RoomStyleAddres;
} public void setRoomStyleAddres(String roomStyleAddres) {
RoomStyleAddres = roomStyleAddres;
} public String getRoomlongrentom() {
return Roomlongrentom;
} public void setRoomlongrentom(String roomlongrentom) {
Roomlongrentom = roomlongrentom;
} @Override
public String toString() {
return "ChaXunJieGuo{" +
"RoomStyleId='" + RoomStyleId + '\'' +
", Unitprice='" + Unitprice + '\'' +
", evaluate='" + evaluate + '\'' +
", Brandname='" + Brandname + '\'' +
", RoomStyleImage=" + RoomStyleImage +
", RoomStyleAddres='" + RoomStyleAddres + '\'' +
", Roomlongrentom='" + Roomlongrentom + '\'' +
", RoomStyleName='" + RoomStyleName + '\'' +
", RoomStar='" + RoomStar + '\'' +
'}';
}
}

其实,后台传来的数据不止那么少对象,我们来看看后台传过来的json格式是什么

[
{
"RoomStyleId":"51",
"RoomStyleName":"商务双床",
"RoomStyleAddres":"佛山市南海区桂澜北路万达广场C座",
"RoomStylePrice":"2720",
"RoomStyleguarantee":"3860",
"RoomStyleLng":"113.156684",
"RoomStyleLat":"23.063305",
"RoomStyleSize":"58",
"RoomStyleHall":"1",
"RoomStyleRoom":"1",
"RoomStyleToilet":"1",
"RoomStyleEquipage":[
"无线WIFI",
"二十四小时热水",
"二十四小时小时监控",
"床上用品",
"冰箱",
"电视",
"二十四小时小时保安值守",
"空调",
"停车场",
"前台问询"
],
"RoomStylePlan":[
{
"duration":"12",
"price":"2720",
"discount":"0.95",
"total":"2584"
},
{
"duration":"11",
"price":"2750",
"discount":"0.95",
"total":"2613"
},
{
"duration":"10",
"price":"2780",
"discount":"0.95",
"total":"2641"
},
{
"duration":"9",
"price":"2800",
"discount":"0.95",
"total":"2660"
},
{
"duration":"8",
"price":"2830",
"discount":"0.95",
"total":"2689"
},
{
"duration":"7",
"price":"2860",
"discount":"0.95",
"total":"2717"
},
{
"duration":"6",
"price":"3150",
"discount":"0.95",
"total":"2993"
},
{
"duration":"5",
"price":"3290",
"discount":"0.95",
"total":"3126"
},
{
"duration":"4",
"price":"3430",
"discount":"0.95",
"total":"3259"
},
{
"duration":"3",
"price":"3580",
"discount":"0.95",
"total":"3401"
},
{
"duration":"2",
"price":"3720",
"discount":"0.95",
"total":"3534"
},
{
"duration":"1",
"price":"3860",
"discount":"0.95",
"total":"3667"
}
],
"RoomStyleMemo":"2513酒店公寓",
"RoomStyleCItyID":"29",
"RoomStyleProvince":"广东省",
"RoomStyleCIty":"佛山市",
"RoomStyleCounty":"南海区",
"DayDeposit":"100",
"Roomlongrentom":"105",
"RoomStyleImage":[
"./uploadimages/59488cab6c39b.jpg",
"./uploadimages/59488cae23476.jpg",
"./uploadimages/59488cb110cb8.jpg",
"./uploadimages/59488cb3ef3cb.jpg"
],
"Brand":{
"Brandid":"4",
"Brandname":"2513酒店公寓",
"Brandmemo":"2513酒店公寓",
"Brandimage":"./uploadimages/5948e73f7f744.png",
"Brandbigimage":"./uploadimages/5948e72801409.jpg",
"Brandminiimage":"./uploadimages/5948e738cc353.png",
"":"./uploadimages/5948e746c84b4.png"
},
"Unitprice":"218",
"RoomStar":"5",
"evaluate":"10",
"RoomServerManager":{
"ServerManagerId":"16",
"ServerManagerImage":"./uploadimages/58b0f4e08c3f0.png",
"ServerManagerName":"吴柯丽",
"ServerManagerPhoneNumber":"18675739089",
"ServerManagerMemo":"南海管家"
}
}]

这样的json数据就只是需要几个属性,不用全部拿取,所以原生解析可以很快取得,Gson要实体类多,但是可以很快取得数据,还有让代码简洁。

以下附上Gson解析json的例子传送门:http://blog.csdn.net/tkwxty/article/details/34474501/

(2)原生解析-----》optJSONObject

private void postRxFooterData_1(final String PhoneNumber, final String StyleId, final String Duration) {
Subscription subscription = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
RequestBody formBody = new FormEncodingBuilder()
.add("PhoneNumber",PhoneNumber)
.add("StyleId",StyleId)
.add("Duration",Duration)
.add("Relet","1")
.build(); final Request request = new Request.Builder()
.url(Common.NEW_Makeorders)
.post(formBody)
.build(); Call call = client.newCall(request);
try {
Response response = call.execute();
subscriber.onNext(response.body().string());
subscriber.onCompleted();
} catch (IOException e) {
e.printStackTrace();
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
} @Override
public void onError(Throwable e) {
} @Override
public void onNext(String s) {
//
try {
JSONObject arr2 = new JSONObject(s);
String dizhi2 = arr2.optString("styleadd");
String styletitle = arr2.optString("styletitle");
String styleprice = arr2.optString("styleprice");//房租
String total = arr2.optString("total");//优惠券抵扣
String handle = arr2.optString("handle");//应付
String wallet = arr2.optString("wallet");//钱包
fengge.setText(styletitle);
dizhi.setText(dizhi2);
fangzhu.setText("¥" + styleprice + "/日");
yingfu.setText("应付房租:¥" + handle);
heji.setText("合计:¥" + total);
qianbao.setText("钱包抵扣:¥"+wallet);
youjui.setText("优惠卷抵扣:¥0.0");
} catch (JSONException e) {
e.printStackTrace();
} } });
mCompositeSubscription.add(subscription);
}

两者的区别

//使用getJSONObject时,如果返回的对象不是JSONObject,抛出JSONException异常
/**
* Returns the value mapped by {@code name} if it exists and is a {@code
* JSONObject}.
* @throws JSONException if the mapping doesn't exist or is not a {@code
* JSONObject}.
*/ public JSONObject getJSONObject(String name) throws JSONException {
Object object = get(name);
if (object instanceof JSONObject) {
return (JSONObject) object;
} else {
throw JSON.typeMismatch(name, object, "JSONObject");
}
} //使用optJSONObject时,当返回结果不是JSONObject时,这里不会抛异常,而是返回null
/**
* Returns the value mapped by {@code name} if it exists and is a {@code
* JSONObject}. Returns null otherwise.
*/
public JSONObject optJSONObject(String name) {
Object object = opt(name);
return object instanceof JSONObject ? (JSONObject) object : null;
}

json原生解析的更多相关文章

  1. Android JSON原生解析的几种思路,以号码归属地,笑话大全,天气预报为例演示

    Android JSON原生解析的几种思路,以号码归属地,笑话大全,天气预报为例演示 今天项目中要实现一个天气的预览,加载的信息很多,字段也很多,所以理清了一下思路,准备独立出来写一个总结,这样对大家 ...

  2. Delphi XE6 原生解析json

    Delphi XE5带了system.json单元,原生提供了json支持类.下面是解析json用法说明: 最简单的JSON大致像这样 { "date":"周二(今天, ...

  3. Android原生生成JSON与解析JSON

    JSON数据是一种轻量级的数据交换格式,在Android中通常应用于client与server交互之间的传输数据.像如今在网上有非常多解析JSON数据的jar包,可是归根究竟用的都是Android原生 ...

  4. iOS - JSON 数据解析

     iOS - JSON 数据解析 前言 NS_CLASS_AVAILABLE(10_7, 5_0) @interface NSJSONSerialization : NSObject @availab ...

  5. iOS开发笔记3:XML/JSON数据解析

    这篇主要总结在iOS开发中XML/JSON数据解析过程用到的方法.XML数据解析主要使用SAX方式的NSXMLParser以及DOM方式的GDataXML,JSON数据解析主要使用NSJSONSeri ...

  6. 《JAVASCRIPT高级程序设计》JSON语法/解析/序列化

    JSON是一种数据格式,不是一种编程语言. 一.语法 JSON语法可以表示以下三种类型的值:简单值.对象.数组. 1.简单值 最简单的JSON数据值就是简单值: 5 "hello world ...

  7. 关于iOS中几种第三方对XML/JSON数据解析的使用

    Json XML 大数据时代,我们需要从网络中获取海量的新鲜的各种信息,就不免要跟着两个家伙打交道,这是两种结构化的数据交换格式.一般来讲,我们会从网络获取XML或者Json格式的数据,这些数据有着特 ...

  8. JMeter 插件 Json Path 解析 HTTP 响应 JSON 数据(转)

    JMeter 是一个不错的负载和性能测试工具,我们也用来做 HTTP API 接口测试.我们的 API 返回结果为 JSON 数据格式.JSON 简介,JSON 教程. JSON 已经成为数据交换格式 ...

  9. plist文件、NSUserDefault 对文件进行存储的类、json格式解析

    ========================== 文件操作 ========================== Δ一 .plist文件 .plist文件是一个属性字典数组的一个文件: .plis ...

随机推荐

  1. jeecms 代码生成 Tools

    本文作者: IIsKei 本文链接: http://www.iskei.cn/posts/50510.html 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议 ...

  2. python collections模块 之 ChainMap

    ChainMap提供了一种多个字典整合的方式,它没有去合并这些字典,而是将这些字典放在一个 maps (一个列表)里,内部实现了很多 dict 的方法,大部分 dict 的方法,ChainMap 都能 ...

  3. sqlserver存储过程事务回滚

    set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER PROCEDURE [dbo].[AddUserOnChannel] ), ), @Channe ...

  4. ch5 vlsms

    Variabel Length Subnet Mask vlsms 较早的路由协议 ripv1 没有为子网准备的字段,子网信息会被丢失. 这意味着如果一个路由器运行着一个rip协议具有一个确定的子网掩 ...

  5. js如何往数组Array中添加元素 (2013-09-04 10

    unshift:将参数添加到原数组开头,并返回数组的长度 pop:删除原数组最后一项,并返回删除元素的值:如果数组为空则返回undefined push:将参数添加到原数组末尾,并返回数组的长度 co ...

  6. JZOJ5883【NOIP2018模拟A组9.25】到不了——动态LCA裸题

    题目描述 Description wy 和 wjk 是好朋友. 今天他们在一起聊天,突然聊到了以前一起唱过的<到不了>. "说到到不了,我给你讲一个故事吧." &quo ...

  7. c++设计模式:适配器模式

    1.主要思想:将一个类的接口转换成客户希望的另外一个接口.Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作.  对于不同的客户我们可以这样使用适配器模式. 2.实现方法: # ...

  8. Trees in a Wood UVA - 10214 欧拉函数模板

    太坑惹,,,没用longlong各种WA #include <iostream> #include <string.h> #include <cstdio> #in ...

  9. beanstalkd 消息队列发邮件

    放入消息 /** * 获取beanstalk实例 * * @staticvar resource|bool $beanstalk * @return resource */ function get_ ...

  10. LintCode 链表倒数第n个节点

    找到单链表倒数第n个节点,保证链表中节点的最少数量为n. 样例 给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1. 分析:设两个指针 p1和p2 ...