Android之Json ((JavaScript Object Notation))文件解析
Json文件格式
对象{},
集合[]
数据类型:数字,字符串,布尔,集合[],对象{},null
数据间隔”,”
问题:相机功能缺失,部分相机功能通过config文件配置,config文件解析错误导致相机功能缺失。
排查原因:修改配置文件过程中,多提交了一个分号“””,相机可正常使用,排查耗时较长。
配置文件缓存在本地,文件路径/odm/......
文件名称:xx_xx_config
文件格式
[
{
},
......
......
{
“Tag”: “value”
“Type”: “value”
“Count”: “value”
“Value”: “value”
}
]
- 工具
android.jar
1.JSONArray
2.FileInputStream
(0)
所有需要配置的key缓存在map中并设置默认值
defaultMap.put(key,defaultValue)
- 获取本地文件IO流
FileInputStream fileInputStream = new FileInputStream (path)
- IO流获取字节流并缓存
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
(3)编码新的字符串
String jsonString = new String(buffer, "UTF-8")
(4)字符串转储至jsonArray
JSONArray jsonArray = new JSONArray(jsonString);
- 获取解析的JsonArray对象
JsonArray.length返回对象数组size
JSONObject jsonObject = jsonArray.getJSONObject(i);
key = jsonObject.getString("VendorTag");
value = jsonObject.getString("Value");
参考链接:
https://blog.youkuaiyun.com/qq_32253371/article/details/78083391?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160671272819724813268905%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=160671272819724813268905&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-2-78083391.pc_first_rank_v2_rank_v28&utm_term=JSONArray&spm=1018.2118.3001.4449
https://blog.youkuaiyun.com/gao_sl/article/details/81699063?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control
源码:
/**
* Creates a new {@code JSONArray} with values from the JSON string.
*
* @param json a JSON-encoded string containing an array.
* @throws JSONException if the parse fails or doesn't yield a {@code
* JSONArray}.
*/
public JSONArray(String json) throws JSONException {
this(new JSONTokener(json));
}
/**
* Creates a new {@code JSONArray} with values from the given primitive array.
*/
public JSONArray(JSONTokener readFrom) throws JSONException {
/*
* Getting the parser to populate this could get tricky. Instead, just
* parse to temporary JSONArray and then steal the data from that.
*/
Object object = readFrom.nextValue();
if (object instanceof JSONArray) {
values = ((JSONArray) object).values;
} else {
throw JSON.typeMismatch(object, "JSONArray");
}
}