无可奈何花落去,似曾相识燕归来 – 晏殊
json语法是JavaScript对象表示法语法的子集
- 数据在名称/值对中
- 数据由逗号分隔
- 花括号保持对象
- 方括号保存数组
JSON的值可以是:
- 数字(整数或者浮点数)
- 字符串(在双引号内)
- 逻辑值(true 或 false)
- 数组(使用方括号[]包围)
- 对象( 使用花括号{}包围)
- null
JSON中有且只有两种结构:对象和数组。
1、对象:对象在js中表示为“{}”括起来的内容,数据结构为
{key:value,key:value,…}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为
对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。2、数组:数组在js中是中括号“[]”括起来的内容,数据结构为
[“java”,”javascript”,”vb”,…],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。
我们先解析本地的json文件 ,之后再解析网络的json文件
程序要解析的数据都放在项目的assets目录下
{"name":"baoqiang", "age":"18", "address":"ganzhou"}
[
{"id":1,"ide":"Eclipse","name":"java"},
{"id":2,"ide":"XCode","name":"Swift"},
{"id":3,"ide":"Visual Studio","name":"C##"}
]
{"name":"baoqiang", "age":"18", "address":"ganzhou",
"languages":[
{"id":1,"ide":"Eclipse","name":"java"},
{"id":2,"ide":"XCode","name":"Swift"},
{"id":3,"ide":"Visual Studio","name":"C##"}
]
}
一. 解析get_data1.json的数据,代码直接放在onCreate方法下执行
try {
//InputStreamReader 将字节输入流转换为字符流
InputStreamReader isr = new InputStreamReader(getAssets().open("get_data1.json"), "UTF-8");
//包装字符流,将字符流放入缓存里
BufferedReader br = new BufferedReader(isr);
String line;
//StringBuilder和StringBuffer功能类似,存储字符串
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
//append 被选元素的结尾(仍然在内部)插入指定内容,缓存的内容依次存放到builder中
builder.append(line);
}
br.close();
isr.close();
//builder.toString()返回表示此序列中数据的字符串
JSONObject root = new JSONObject(builder.toString());
System.out.println("name= " + root.getString("name") +
";age= " + root.getInt("age") +
";address= " + root.getString("address"));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
二. 解析get_data2.json的数据
try {
InputStreamReader isr = new InputStreamReader(getAssets().open("get_data2.json"), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
br.close();
isr.close();
JSONArray array = new JSONArray(builder.toString());
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 (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
三.解析get_data3.json数据
try {
InputStreamReader isr = new InputStreamReader(getAssets().open("get_data3.json"), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
br.close();
isr.close();
JSONObject root = new JSONObject(builder.toString());
System.out.println("name= " + root.getString("name") +
" age= " + root.getInt("age") +
" address= " + root.getString("address"));
//读取多个数据
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("name= " + lan.getString("name"));
System.out.println("ide= " + lan.getString("ide"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
注意
lan.getInt(“id”)和getJSONObject();还可以用lan.optInt(“id”)和optJSONObject()表示,功能相同,返回值不同,,get会有null值异常抛出
如果解析数组和对象类型数不正确,则会报错
System.err: org.json.JSONException …….type org.json.JSONObject cannot be converted to JSONArray
System.err: at org.json.JSON.typeMismatch(JSON.java:111)
网络服务器选用Tomcat服务器
我们把get_data3.json文件放在C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT目录下,并开启Tomcat服务器
大可不必用eclipse建立动态网站来发布文件
下图是开启后从浏览器查看发布的数据
{"name":"baoqiang", "age":"18", "address":"ganzhou",
"languages":[
{"id":1,"ide":"Eclipse","name":"java"},
{"id":2,"ide":"XCode","name":"Swift"},
{"id":3,"ide":"Visual Studio","name":"C##"}
]
}
<uses-permission android:name="android.permission.INTERNET"/>
代码
注意
联网需要开子线程,如果要更新UI,还需要在子线程中用runOnUiThread()或者Handler来处理
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("开始");
new Thread() {
@Override
public void run() {
try {
//注意填写自己的IPv4路径,不能用localhost
String path = "http://192.168.1.44:8080/get_data3.json";
URL url = new URL(path);
System.out.println(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
System.out.println("连接成功");
InputStream in = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
//InputStreamReader isr = new InputStreamReader(getAssets().open("get_data.json"),"UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
//StringBuilder 缓存区 StringBuffer
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
br.close();
isr.close();
JSONObject root = new JSONObject(builder.toString());
System.out.println("name= " + root.getString("name") +
" age= " + root.getInt("age") +
" address= " + root.getString("address"));
//读取多个数据
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("name= " + lan.getString("name"));
System.out.println("ide= " + lan.getString("ide"));
}
} else {
System.out.println("连接失败");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
}
需要编写的格式文件
{"name":"baoqiang", "age":"18", "address":"ganzhou",
"languages":[
{"id":1,"ide":"Eclipse","name":"java"},
{"id":2,"ide":"XCode","name":"Swift"},
{"id":3,"ide":"Visual Studio","name":"C##"}
]
}
编写代码
try {
JSONObject root = new JSONObject();
root.put("name", "baoqiang");
root.put("age", "12");
root.put("adress", "guanzhou");
/**
* languages三行值
*/
JSONObject lan1 = new JSONObject();
lan1.put("id", "1");
lan1.put("ide", "Eclipse");
lan1.put("name", "java");
JSONObject lan2 = new JSONObject();
lan2.put("id", "2");
lan2.put("ide", "Xcode");
lan2.put("name", "swift");
JSONObject lan3 = new JSONObject();
lan3.put("id", "3");
lan3.put("ide", "Studio");
lan3.put("name", "C#");
JSONArray array = new JSONArray();
array.put(lan1);
array.put(lan2);
array.put(lan3);
root.put("languages", array);
System.out.println(root.toString());
} catch (JSONException e) {
e.printStackTrace();
}
结果
json本地解析-源码:https://github.com/PengHongfu/Json_Local.git
json网络解析-源码:https://github.com/PengHongfu/Json_net.git
http://blog.isming.me/blog/2014/06/04/parse-json-in-android/