我是做Andriod开发的,在客户端和服务器端进行数据交互通常是二种 格式,一种是xml,一种是json,在实际项目中绝大部分都是通过json格式进行前端和后端的交互,主要是基于2方面考虑
第一:json使用起来简单,解析起来也方面
第二:比xml省流量
先介绍json一些基础的常识:
JSON,全称是JavaScript Object Notation。它是基于JavaScript编程语言ECMA-262 3rd Edition-December 1999标准的一种轻量级的数据交换格式,主要用于用于跟服务器进行交换数据。跟XML相类似,它独立于语言,在跨平台数据传输上有很大的优势,
json基本的结构:
JSON建构有两种结构:
1. “名称/值”对的集合,名称和值之间使用“:”隔开,一般的形式是:用花括号{"key":"value"},这是最简单的json数据结构
比如:{name:value} 实例:{"name":"zhangsan"}
现在我们来建个Android项目来验证并解析下
把json数据放在string.xml文件中<string name="json">{"name":"zhangsan"}</string>
解析关键代码:
String json = getString(R.string.json);
try {
JSONObject obj = new JSONObject(json);
String name = obj.getString("name");
Log.e("MainActivity", "name="+name);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我们看看打印的log日记:
现在我们可以把value值改为其它数据类型,比如改成int类型<string name="json">{"name":2}</string>
解析代码:
String json = getString(R.string.json);
try {
JSONObject obj = new JSONObject(json);
int name = obj.getInt("name");
Log.e("MainActivity", "name="+name);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
解析结果:
一个key是字符串还可以对应一个对象,比如:
{
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
}
}
key是address 值是一个对象,上面的字符串放在assert文件夹下 在这文件夹下创建一个json.txt文件存放上面的字符串
在你代码中先获取json字符串 然后就可以解析了
代码:
try {
InputStream in = getAssets().open("json.txt");
String json = readFromStream(in);
JSONObject obj = new JSONObject(json);
JSONObject ja = obj.getJSONObject("address");
String a = ja.getString("streetAddress");
String b = ja.getString("city");
String c = ja.getString("state");
String d= ja.getString("postalCode");
Log.i("MainActivity", "a="+a);
Log.i("MainActivity", "b="+b);
Log.i("MainActivity", "c="+c);
Log.i("MainActivity", "d="+d);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 把流转成字符串
* @param is
* @return
* @throws Exception
*/
public static String readFromStream(InputStream is) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
is.close();
String result = baos.toString();
baos.close();
return result;
}
打印的结果如图:
那么对应的javabean对象Address是这样的
public class Address {
private String streetAddress;
private String city;
private String state;
private String postalCode;
}
那么一个key还可以对应一个串行表,
比如:
{"singers":[{'id':02,'name':'tom','gender':'nan'},{'id':03,'name':'jerry','gender':nan'},{'id':04,'name':'jim','gender':'nan'},{'id':05,'name':'lily','gender':'nv'}]}
也就是多个对象:
还是和上面的一样,把json数据写到assert/json.txt中
代码:
try {
InputStream in = getAssets().open("json.txt");
String json = readFromStream(in);
Log.e("MainActivity", "json="+json);
JSONArray jsonObjs = new JSONObject(json).getJSONArray("singers");
String s = "";
for(int i = 0; i < jsonObjs.length() ; i++){
JSONObject jsonObj = jsonObjs.getJSONObject(i);
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String gender = jsonObj.getString("gender");
Log.e("MainActivity", "id="+id);
Log.e("MainActivity", "name="+name);
Log.e("MainActivity", "gender="+gender);
}
} catch (Exception e) {
e.printStackTrace();
}
结果如图:
在这要注意:
多个对象用[]格式为:
[{对象1},{对象2},{对象3}]
好了 这是最简单的json 也就是key/value的形式 这个value可以是一个值可以是一个字符串,一个数值,一个对象,一个布尔值,一个有串行表,或者一个null值
上面的例子都讲的很详细了
2.值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
上面其实已经讲了关于一个key对应一个数组的数组对象,现在再讲一种,也是数组不过数组中包括多个对象
json串:
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }
我们分析下
“programmers”对应一个数组{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
数组中有三个对象
关键代码;
try {
InputStream in = getAssets().open("json.txt");
String json = readFromStream(in);
Log.e("MainActivity", "json="+json);
JSONArray jsonObjs = new JSONObject(json).getJSONArray("programmers");
for(int i = 0; i < jsonObjs.length() ; i++){
JSONObject jsonObj = jsonObjs.getJSONObject(i);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("firstName");
String lastName = jsonObj.getString("lastName");
Log.e("MainActivity", "id="+email);
Log.e("MainActivity", "name="+firstName);
Log.e("MainActivity", "gender="+lastName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 把流转成字符串
* @param is
* @return
* @throws Exception
*/
public static String readFromStream(InputStream is) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
is.close();
String result = baos.toString();
baos.close();
return result;
}
现在来一个长点的字符串 学会了 简单了
{
"status": 0,
"message": "ok",
"info": {
"copyright": {
"text": "@2014 Baidu - Data",
"imageUrl": "http:\/\/api.map.baidu.com\/images\/copyright_logo.png"
}
},
"result": {
"elements": [
{
"distance": {
"text": "10.3\u516c\u91cc",
"value": 10274
},
"duration": {
"text": "26\u5206\u949f",
"value": 1582
}
},
{
"distance": {
"text": "1213.8\u516c\u91cc",
"value": 1213844
},
"duration": {
"text": "13.2\u5c0f\u65f6",
"value": 47552
}
},
{
"distance": {
"text": "9.7\u516c\u91cc",
"value": 9701
},
"duration": {
"text": "21\u5206\u949f",
"value": 1243
}
},
{
"distance": {
"text": "1219.5\u516c\u91cc",
"value": 1219544
},
"duration": {
"text": "13.3\u5c0f\u65f6",
"value": 47876
}
}
]
}
}
这是百度地图的字符串,之前感觉很难,现在看懂了json,so easy
代码:
try {
InputStream in = getAssets().open("json.txt");
String json = readFromStream(in);
Log.e("MainActivity", "json="+json);
JSONObject jo = new JSONObject(json).getJSONObject("result");
JSONArray ja = jo.getJSONArray("elements");
String value = ja.getJSONObject(0).getJSONObject("distance").getString("value");
Log.e("MainActivity", "value="+value);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 把流转成字符串
* @param is
* @return
* @throws Exception
*/
public static String readFromStream(InputStream is) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
is.close();
String result = baos.toString();
baos.close();
return result;
}
ok了