JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式 具体参照百度百科。
下面主要是举一个操作的例子来说明JSON的操作。从某个地方获取到一个JSON数据(可以是网络,也可以是自己保存数据时通过JSON保存),然后解析JSON数据。
JSON 语法
JSON 语法规则
JSON 语法是 JavaScript 对象表示语法的子集。
-
数据在名称/值对中
-
数据由逗号分隔
-
花括号保存对象
-
方括号保存数组
JSON 名称/值对
JSON 数据的书写格式是:名称/值对。
名称/值对组合中的名称写在前面(在双引号中),值对写在后面(同样在双引号中),中间用冒号隔开:
"firstName":"John"
|
这很容易理解,等价于这条 JavaScript 语句:
firstName="John"
JSON 值可以是:
-
数字(整数或浮点数)
-
字符串(在双引号中)
-
逻辑值(true 或 false)
-
数组(在方括号中)
-
对象(在花括号中)
-
null
先看一个JSONObject,在这个示例中,只有一个名为 people的变量,值是包含三个条目的数组,每个条目是一个人的记录,其中包含名、姓和电子邮件地址。上面的示例演示如何用括号将记录组合成一个值。当然,可以使用相同的语法表示多个值(每个值包含多个记录)
{
"people":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
]
}
解析JSON一般我们需要知道JSON的数据结构,
而如果不知道JSON的结构而去解析JSON的话,那简直是噩梦。费时费力不说,代码也会变得冗余拖沓,得到的结果也不尽人意。但是这样也不影响众多前台开发人员选择JSON。toJSONString()就可以看到JSON的字符串结构。常用JSON的人看到这个字符串之后,就对JSON的结构很明了了,就更容易的操作JSON。
1、先定义一个数据模型对象。这个怎么定义,如果只是直接通过JSON保存再读取解析的话,则可以根据自己喜好定义。如果是通过其他地方得到JSON数据,则需要先通过toJSONString得到的数据进行分析。
假设得到的数据是这样的 {person:{id:1,name:wyd,address:shenzhen}} 还有数组 {persons:[{
id:1,name:wyd,
address:shenzhen},{
id:2,name:cxx,
address:shenzhen}] }
package com.example.android0602_json.domain;
import org.json.JSONException;
import org.json.JSONObject;
public class Person {
<span style="white-space:pre"> </span>public static final String JSON_ID = "id";
<span style="white-space:pre"> </span>public static final String JSON_NAME = "name";
<span style="white-space:pre"> </span>public static final String JSON_ADDRESS = "address";
<span style="white-space:pre"> </span>private int id;
<span style="white-space:pre"> </span>private String name;
<span style="white-space:pre"> </span>private String address;
<span style="white-space:pre"> </span>public Person() {
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public Person(int id, String name, String address) {
<span style="white-space:pre"> </span>this.id = id;
<span style="white-space:pre"> </span>this.name = name;
<span style="white-space:pre"> </span>this.address = address;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>/** 通过JSON得到对象 感觉有点像SharedPreferences */
<span style="white-space:pre"> </span>public Person(JSONObject json) throws JSONException {
<span style="white-space:pre"> </span>id = json.getInt(JSON_ID);
<span style="white-space:pre"> </span>name = json.getString(JSON_NAME);
<span style="white-space:pre"> </span>address = json.getString(JSON_ADDRESS);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public int getId() {
<span style="white-space:pre"> </span>return id;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void setId(int id) {
<span style="white-space:pre"> </span>this.id = id;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public String getName() {
<span style="white-space:pre"> </span>return name;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void setName(String name) {
<span style="white-space:pre"> </span>this.name = name;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public String getAddress() {
<span style="white-space:pre"> </span>return address;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void setAddress(String address) {
<span style="white-space:pre"> </span>this.address = address;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>/** 对象进行JSON化,感觉有点像SharedPreferences */
<span style="white-space:pre"> </span>public JSONObject toJSON() throws JSONException {
<span style="white-space:pre"> </span>JSONObject json = new JSONObject();
<span style="white-space:pre"> </span>json.put(JSON_ID, id);
<span style="white-space:pre"> </span>json.put(JSON_NAME, name);
<span style="white-space:pre"> </span>json.put(JSON_ADDRESS, address);
<span style="white-space:pre"> </span>return json;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public String toString() {
<span style="white-space:pre"> </span>return "Person [address=" + address + ", id=" + id + ", name=" + name
<span style="white-space:pre"> </span>+ "]";
<span style="white-space:pre"> </span>}
}
下面是json进行解析的工具类。
public class JsonTools {
public JsonTools() {
}
public static Person getPerson(String key, String jsonString) {
Person person = null;
try {
JSONObject jsonObject = new JSONObject(jsonString);//总的是一个JSONObject,里面可以有其他的JSONObject
JSONObject personObject = jsonObject.getJSONObject(key); //找到key这个JSON对象
person = new Person(personObject);
} catch (Exception e) {
}
return person;
}
public static List<Person> getPersons(String key, String jsonString) {
List<Person> list = new ArrayList<Person>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key); // 找到key这个JSON数组
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Person person = new Person(jsonObject2);
list.add(person);
}
} catch (Exception e) {
}
return list;
}
public static void savePersons(ArrayList<Person> persons, Context context)
throws JSONException, IOException {
JSONArray array = new JSONArray();
for (Person p : persons)
array.put(p.toJSON());
Writer writer = null;
try {
OutputStream out = context.openFileOutput("json_data",
Context.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} finally {
if (writer != null)
writer.close();
}
}
}
/**
*<span style="white-space:pre"> </span>两个问题点:
* 1、需要加入网络权限
* 2、网络不能在主线程上操作
* 3、网址必须是 192.168.10.101 不能是127或者是localhost
*/
import java.util.List;
import java.util.Map;
import com.example.android0602_json.domain.Person;
import com.example.android0602_json.http.HttpUtils;
import com.example.android0602_json.json.JsonTools;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
<span style="white-space:pre"> </span>private Button person, persons;
<span style="white-space:pre"> </span>private static final String TAG = "MainActivity";
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public void onCreate(Bundle savedInstanceState) {
<span style="white-space:pre"> </span>super.onCreate(savedInstanceState);
<span style="white-space:pre"> </span>setContentView(R.layout.main);
<span style="white-space:pre"> </span>person = (Button) this.findViewById(R.id.person);
<span style="white-space:pre"> </span>persons = (Button) this.findViewById(R.id.persons);
<span style="white-space:pre"> </span>person.setOnClickListener(this);
<span style="white-space:pre"> </span>persons.setOnClickListener(this);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public void onClick(View v) {
<span style="white-space:pre"> </span>switch (v.getId()) {
<span style="white-space:pre"> </span>case R.id.person:
<span style="white-space:pre"> </span>String jsonString = "{person:{id:1,name:wyd,address:shenzhen}}";
<span style="white-space:pre"> </span>Person person = JsonTools.getPerson("person", jsonString);
<span style="white-space:pre"> </span>System.out.println(person.toString());
<span style="white-space:pre"> </span>break;
<span style="white-space:pre"> </span>case R.id.persons:
<span style="white-space:pre"> </span>String jsonString2 = "{persons:[{id:1,name:wyd,address:shenzhen},{id:2,name:cxx,address:shenzhen}] }";
<span style="white-space:pre"> </span>List<Person> list2 = JsonTools.getPersons("persons", jsonString2);
<span style="white-space:pre"> </span>System.out.println(list2.toString());
<span style="white-space:pre"> </span>break;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}
服务器的创建。在eclipse里面新建一个动态web工程。工程名字为jsonprj。里面增加一些创建JSON数据的功能。最后创建一个
HttpServlet。内容如下。访问格式分别:http://localhost/jsonprj/JsonAction?action_flag=person 会返回完整的JSON数据。
@WebServlet("/JsonAction")
public class JsonAction extends HttpServlet {
private JsonService service;
public JsonAction() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String jsonString = "";
/** 这里可以获取参数 */
String action_flag = request.getParameter("action_flag");
if (action_flag == null) {
jsonString = JsonTools.createJsonString(service.getListMaps());
} else if (action_flag.equals("person")) {
jsonString = JsonTools.createJsonString(service.getPerson());
} else if (action_flag.equals("persons")) {
jsonString = JsonTools.createJsonString(service.getlistPerson());
} else if (action_flag.equals("liststring")) {
jsonString = JsonTools.createJsonString(service.getListString());
} else if (action_flag.equals("listmap")) {
jsonString = JsonTools.createJsonString(service.getListMaps());
}
out.println(jsonString);
out.flush();
out.close();
}
public void init() throws ServletException {
service = new JsonService();
}
}