json - JSON
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式, 是目前最见的数据交换方式, 具体请参考 https://baike.baidu.com/item/JSON 或 https://en.wikipedia.org/wiki/JSON .
TiJOS Framework中的JSON实现来自https://github.com/stleary/JSON-java, 支持JSONArray, JSONObject, JSONString, 具体可参考相关资料.
Java包
tijos.framework.util
主要类说明
类 | 说明 |
---|---|
JSONObject | JSON对象, 可用于构造JSON字符串 |
JSONArray | JSON数组 |
JSONTokener | JSON解析类 |
具体使用方法可参考 https://blog.csdn.net/jediael_lu/article/details/25779087
注意,钛极OS的JSON不支持与反射有关的方法
例程:
- JSON格式编码
//Generate JSON string
JSONObject studentJSONObject = new JSONObject();
try {
studentJSONObject.put("name", "Jason");
studentJSONObject.put("id", 20130001);
studentJSONObject.put("phone", "13579246810");
} catch (JSONException e) {
e.printStackTrace();
}
- JSON格式解码
final String JSON =
"{" +
" \"phone\" : [\"12345678\", \"87654321\"]," +
" \"name\" : \"jack\"," +
" \"age\" : 21," +
" \"address\" : { \"country\" : \"china\", \"province\" : \"beijing\" }," +
" \"married\" : false," +
"}";
try {
JSONTokener jsonTokener = new JSONTokener(JSON);
JSONObject person = (JSONObject) jsonTokener.nextValue();
JSONArray phoneArray = person.getJSONArray("phone");
for(int i = 0; i < phoneArray.length(); i ++)
{
System.out.println("Phone" + i);
System.out.println(phoneArray.getString(i));
}
System.out.println(person.getString("name"));
System.out.println(person.getInt("age"));
JSONObject addr = person.getJSONObject("address");
System.out.println(addr.getString("country"));
System.out.println(addr.getString("province"));
System.out.println(person.getBoolean("married"));
} catch (JSONException ex) {
ex.printStackTrace();
}