大家好,今天给大家分享下Android解析Json的例子,我这里自己安装了Tomcat,让自己电脑充当下服务器,最重要的是,返回结果自己可以随便修改。
首先看下Json的定义,以及它和XML的比较:
JSON的定义:
一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org
JSON Vs XML
1.JSON和XML的数据可读性基本相同
2.JSON和XML同样拥有丰富的解析手段
3.JSON相对于XML来讲,数据的体积小
4.JSON与JavaScript的交互更加方便
5.JSON对数据的描述性比XML较差
6.JSON的速度要远远快于XML.
Tomcat安装:
Tomcat下载地址http://tomcat.apache.org/ 下载后安装,如果成功,启动Tomcat,然后在浏览器里输入:http://localhost:8080/index.jsp,会有个Tomcat首页界面,
我们在Tomcat安装目录下webapps\ROOT下找到index.jsp,然后新建一个index2.jsp,用记事本或者什么的,编辑内容如下:
1 |
{students:[{name: '魏祝林' ,age: 25 },{name: '阿魏' ,age: 26 }], class : '三年二班' }
|
然后我们在浏览器里输入:http://localhost:8080/index2.jsp返回的结果如下(这就模拟出后台返回的数据了): 新建一个Android工程JsonDemo. 工程目录如下: 这里我封装了一个JSONUtil工具类,代码如下:
001 |
package com.tutor.jsondemo;
|
002 |
import java.io.IOException;
|
003 |
import java.io.InputStreamReader;
|
004 |
import java.io.UnsupportedEncodingException;
|
005 |
import org.apache.http.HttpEntity;
|
006 |
import org.apache.http.HttpResponse;
|
007 |
import org.apache.http.client.methods.HttpGet;
|
008 |
import org.apache.http.impl.client.DefaultHttpClient;
|
009 |
import org.apache.http.params.BasicHttpParams;
|
010 |
import org.apache.http.protocol.HTTP;
|
011 |
import org.json.JSONException;
|
012 |
import org.json.JSONObject;
|
013 |
import android.util.Log;
|
015 |
* @author frankiewei. |
018 |
public class JSONUtil {
|
019 |
private static final String TAG = "JSONUtil" ;
|
024 |
* @throws JSONException |
025 |
* @throws ConnectionException |
027 |
public static JSONObject getJSON(String url) throws JSONException, Exception {
|
028 |
return new JSONObject(getRequest(url));
|
031 |
* 向api发送get请求,返回从后台取得的信息。 |
036 |
protected static String getRequest(String url) throws Exception {
|
037 |
return getRequest(url, new DefaultHttpClient( new BasicHttpParams()));
|
040 |
* 向api发送get请求,返回从后台取得的信息。 |
046 |
protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
|
047 |
String result = null ;
|
049 |
HttpGet getMethod = new HttpGet(url);
|
050 |
Log.d(TAG, "do the getRequest,url=" +url+ "" );
|
053 |
HttpResponse httpResponse = client.execute(getMethod); |
055 |
statusCode = httpResponse.getStatusLine().getStatusCode(); |
056 |
Log.d(TAG, "statuscode = " +statusCode);
|
058 |
result = retrieveInputStream(httpResponse.getEntity()); |
059 |
} catch (Exception e) {
|
060 |
Log.e(TAG, e.getMessage()); |
061 |
throw new Exception(e);
|
068 |
* 处理httpResponse信息,返回String |
073 |
protected static String retrieveInputStream(HttpEntity httpEntity) {
|
074 |
int length = ( int ) httpEntity.getContentLength();
|
077 |
if (length < 0 ) length = 10000 ;
|
078 |
StringBuffer stringBuffer = new StringBuffer(length);
|
080 |
InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
|
081 |
char buffer[] = new char [length];
|
083 |
while ((count = inputStreamReader.read(buffer, 0 , length - 1 )) > 0 ) {
|
084 |
stringBuffer.append(buffer, 0 , count);
|
086 |
} catch (UnsupportedEncodingException e) {
|
087 |
Log.e(TAG, e.getMessage()); |
088 |
} catch (IllegalStateException e) {
|
089 |
Log.e(TAG, e.getMessage()); |
090 |
} catch (IOException e) {
|
091 |
Log.e(TAG, e.getMessage()); |
093 |
return stringBuffer.toString();
|
096 |
package com.tutor.jsondemo;
|
097 |
import java.io.IOException;
|
098 |
import java.io.InputStreamReader;
|
099 |
import java.io.UnsupportedEncodingException;
|
100 |
import org.apache.http.HttpEntity;
|
101 |
import org.apache.http.HttpResponse;
|
102 |
import org.apache.http.client.methods.HttpGet;
|
103 |
import org.apache.http.impl.client.DefaultHttpClient;
|
104 |
import org.apache.http.params.BasicHttpParams;
|
105 |
import org.apache.http.protocol.HTTP;
|
106 |
import org.json.JSONException;
|
107 |
import org.json.JSONObject;
|
108 |
import android.util.Log;
|
110 |
* @author frankiewei. |
113 |
public class JSONUtil {
|
115 |
private static final String TAG = "JSONUtil" ;
|
121 |
* @throws JSONException |
122 |
* @throws ConnectionException |
124 |
public static JSONObject getJSON(String url) throws JSONException, Exception {
|
126 |
return new JSONObject(getRequest(url));
|
130 |
* 向api发送get请求,返回从后台取得的信息。 |
135 |
protected static String getRequest(String url) throws Exception {
|
136 |
return getRequest(url, new DefaultHttpClient( new BasicHttpParams()));
|
140 |
* 向api发送get请求,返回从后台取得的信息。 |
146 |
protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
|
147 |
String result = null ;
|
149 |
HttpGet getMethod = new HttpGet(url);
|
150 |
Log.d(TAG, "do the getRequest,url=" +url+ "" );
|
153 |
HttpResponse httpResponse = client.execute(getMethod); |
155 |
statusCode = httpResponse.getStatusLine().getStatusCode(); |
156 |
Log.d(TAG, "statuscode = " +statusCode);
|
158 |
result = retrieveInputStream(httpResponse.getEntity()); |
159 |
} catch (Exception e) {
|
160 |
Log.e(TAG, e.getMessage()); |
161 |
throw new Exception(e);
|
169 |
* 处理httpResponse信息,返回String |
174 |
protected static String retrieveInputStream(HttpEntity httpEntity) {
|
176 |
int length = ( int ) httpEntity.getContentLength();
|
179 |
if (length < 0 ) length = 10000 ;
|
180 |
StringBuffer stringBuffer = new StringBuffer(length);
|
182 |
InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
|
183 |
char buffer[] = new char [length];
|
185 |
while ((count = inputStreamReader.read(buffer, 0 , length - 1 )) > 0 ) {
|
186 |
stringBuffer.append(buffer, 0 , count);
|
188 |
} catch (UnsupportedEncodingException e) {
|
189 |
Log.e(TAG, e.getMessage()); |
190 |
} catch (IllegalStateException e) {
|
191 |
Log.e(TAG, e.getMessage()); |
192 |
} catch (IOException e) {
|
193 |
Log.e(TAG, e.getMessage()); |
195 |
return stringBuffer.toString();
|
编写主Activity代码JSONDemoActivity,代码如下:
001 |
package com.tutor.jsondemo;
|
002 |
import org.json.JSONArray;
|
003 |
import org.json.JSONException;
|
004 |
import org.json.JSONObject;
|
005 |
import android.app.Activity;
|
006 |
import android.os.Bundle;
|
007 |
import android.widget.TextView;
|
008 |
public class JSONDemoActivity extends Activity {
|
010 |
* 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2 |
012 |
private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp" ;
|
013 |
private TextView mStudentTextView;
|
014 |
private TextView mClassTextView;
|
016 |
public void onCreate(Bundle savedInstanceState) {
|
017 |
super .onCreate(savedInstanceState);
|
018 |
setContentView(R.layout.main); |
024 |
private void setupViews(){
|
025 |
mStudentTextView = (TextView)findViewById(R.id.student); |
026 |
mClassTextView = (TextView)findViewById(R.id.classes); |
029 |
JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL); |
031 |
JSONArray mJsonArray = mJsonObject.getJSONArray( "students" );
|
033 |
JSONObject firstStudent = mJsonArray.getJSONObject( 0 );
|
035 |
String classes = mJsonObject.getString( "class" );
|
036 |
String studentInfo = classes + "共有 " + mJsonArray.length() + " 个学生."
|
037 |
+ "第一个学生姓名: " + firstStudent.getString( "name" )
|
038 |
+ " 年龄: " + firstStudent.getInt( "age" );
|
039 |
mStudentTextView.setText(studentInfo); |
040 |
mClassTextView.setText( "班级: " + classes);
|
041 |
} catch (JSONException e) {
|
043 |
} catch (Exception e) {
|
048 |
package com.tutor.jsondemo;
|
049 |
import org.json.JSONArray;
|
050 |
import org.json.JSONException;
|
051 |
import org.json.JSONObject;
|
052 |
import android.app.Activity;
|
053 |
import android.os.Bundle;
|
054 |
import android.widget.TextView;
|
055 |
public class JSONDemoActivity extends Activity {
|
057 |
* 访问的后台地址,这里访问本地的不能用127.0.0.1应该用10.0.2.2 |
059 |
private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp" ;
|
061 |
private TextView mStudentTextView;
|
063 |
private TextView mClassTextView;
|
067 |
public void onCreate(Bundle savedInstanceState) {
|
068 |
super .onCreate(savedInstanceState);
|
069 |
setContentView(R.layout.main); |
075 |
private void setupViews(){
|
076 |
mStudentTextView = (TextView)findViewById(R.id.student); |
077 |
mClassTextView = (TextView)findViewById(R.id.classes); |
081 |
JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL); |
084 |
JSONArray mJsonArray = mJsonObject.getJSONArray( "students" );
|
086 |
JSONObject firstStudent = mJsonArray.getJSONObject( 0 );
|
088 |
String classes = mJsonObject.getString( "class" );
|
092 |
String studentInfo = classes + "共有 " + mJsonArray.length() + " 个学生."
|
093 |
+ "第一个学生姓名: " + firstStudent.getString( "name" )
|
094 |
+ " 年龄: " + firstStudent.getInt( "age" );
|
096 |
mStudentTextView.setText(studentInfo); |
098 |
mClassTextView.setText( "班级: " + classes);
|
099 |
} catch (JSONException e) {
|
101 |
} catch (Exception e) {
|
这里用到的布局文件main.xml代码如下:
01 |
view plaincopyprint?<?xml version= "1.0" encoding= "utf-8" ?>
|
02 |
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
|
03 |
android:layout_width= "fill_parent"
|
04 |
android:layout_height= "fill_parent"
|
05 |
android:orientation= "vertical" >
|
07 |
android:id= "@+id/student"
|
08 |
android:layout_width= "fill_parent"
|
09 |
android:layout_height= "wrap_content"
|
10 |
android:text= "@string/hello" />
|
12 |
android:id= "@+id/classes"
|
13 |
android:layout_width= "fill_parent"
|
14 |
android:layout_height= "wrap_content"
|
17 |
<?xml version= "1.0" encoding= "utf-8" ?>
|
18 |
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
|
19 |
android:layout_width= "fill_parent"
|
20 |
android:layout_height= "fill_parent"
|
21 |
android:orientation= "vertical" >
|
23 |
android:id= "@+id/student"
|
24 |
android:layout_width= "fill_parent"
|
25 |
android:layout_height= "wrap_content"
|
26 |
android:text= "@string/hello" />
|
28 |
android:id= "@+id/classes"
|
29 |
android:layout_width= "fill_parent"
|
30 |
android:layout_height= "wrap_content"
|
最后要在AndroidMainfest.xml中添加访问网络权限:
01 |
view plaincopyprint?<?xml version= "1.0" encoding= "utf-8" ?>
|
02 |
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
|
03 |
package = "com.tutor.jsondemo"
|
04 |
android:versionCode= "1"
|
05 |
android:versionName= "1.0" >
|
06 |
<uses-permission android:name= "android.permission.INTERNET" ></uses-permission>
|
08 |
android:icon= "@drawable/ic_launcher"
|
09 |
android:label= "@string/app_name" >
|
11 |
android:name= ".JSONDemoActivity"
|
12 |
android:label= "@string/app_name" >
|
14 |
<action android:name= "android.intent.action.MAIN" />
|
15 |
<category android:name= "android.intent.category.LAUNCHER" />
|
20 |
<?xml version= "1.0" encoding= "utf-8" ?>
|
21 |
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
|
22 |
package = "com.tutor.jsondemo"
|
23 |
android:versionCode= "1"
|
24 |
android:versionName= "1.0" >
|
25 |
<uses-permission android:name= "android.permission.INTERNET" ></uses-permission>
|
27 |
android:icon= "@drawable/ic_launcher"
|
28 |
android:label= "@string/app_name" >
|
30 |
android:name= ".JSONDemoActivity"
|
31 |
android:label= "@string/app_name" >
|
33 |
<action android:name= "android.intent.action.MAIN" />
|
34 |
<category android:name= "android.intent.category.LAUNCHER" />
|
分享到:
相关推荐
Android 解析后台返回为Json数据的简单例子
ajax中若没有定义dataType : “json”,需要eval(“(“+data+”)...以上这篇JS解析后台返回的JSON格式数据实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持软件开发网。
4. android的apk给你说完成http数据请求和json获取解析。 5. 把index.php部署到你的php服务器. 6. 修改MainActivity.java中的 final private String DATA_URL = "http://192.168.1.5/test/index.php"; 指向你部署好...
Android_JSON数据解析 博客里面的Demo
Android通过gson自动解析服务器返回的json数据
eclipse项目。获取raw文件下的json文件。无需编写json数据里面key值的实体类,动态获取里面的键值对的值。并在列表显示
android采用json解析数据的实例
Android 实用的数据json数据解析封装类,能快速解析任何形式json数据
老罗android 解析json数据源码
在模块对应的包名下创建JSON数据对应的实体类WeatherInfo类,实体类中的成员名称要与JSON数组的key值一致,并为每个属性添加get和set方法。public String getTemp() {return temp;}public void setTemp(String temp)...
只需要将dt传过来就能够生成json类型数据
Android Studio下使用Google Gson解析Json数据示例
android实现解析Google地图API json数据
WebView布局使用,okHTTP访问解析服务器返回的json/xml数据。
android之json和gson数据解析最完整的代码例子(包括各种样式的json数据) 本人在2.3.3模拟器上已亲测可以运行。最适合学习json 或gson数据解析的初学者。
Android解析Json数据的PPT和源码
Android 将网络返回的Json数据格式化,并且封装了Retrofit的网络请求框架。
使用Java为Android项目写后台传输Json数据
android网络解析数据,JSON解析数据的方法
Android中Json的数据解析博文源码。博文请关注:http://blog.csdn.net/yegongheng