Android本地Json配置檔案實現筆記
阿新 • • 發佈:2018-12-31
簡述
開發中不可避免會遇到這樣的需求,通過json作為配置檔案配置app(比如本地資料庫的構建等)。
1.Json格式
假設有這樣一個需求:作為配置檔案,我們設計了幾種獎品用於使用者抽獎。
以一個一般的Json格式為例:
{
"filed": true, //配置引數,本例不用只做示範
"rewards": [ //獎品列表
{
"name": "脆脆鯊", //獎品名稱
"probability": "0.35", //中獎概率
"image_res": 1, //獎品icon
"reward_serial": "21313133"//獎品serial,用於api請求等
},
{
"name": "東方神牛",
"probability": "0.45",
"image_res": 2,
"reward_serial": "21313134"
},
{
"name": "旺仔牛奶",
"probability": "0.2",
"image_res": 3,
"reward_serial": "21313135"
}
]
}
2.序列化
為了更清楚的描述,我們建立一個Reward類,用來表示這些獎品物件
public class Reward {
public String name;
public float probability;
public int imageResource;
public String serial;
public Reward(String name, float probability, int imageResource, String rewardSerial) {
this.name = name;
this .probability = probability;
this.imageResource = imageResource;
this.Serial = rewardSerial;
}
}
接下來就可以解析json配置檔案然後序列化為JsonObject了。
//獲取json資料
String rewardJson = "";
String rewardnJsonLine;
//assets資料夾下json檔案的路徑->開啟json檔案
BufferedReader bufferedReader = new BufferedReader(newInputStreamReader(context.getAssets().open("db/reward.json")));
while ((rewardJsonLine = bufferedReader.readLine()) != null) {
rewardJson += rewardJsonLine;
}
//序列化json資料
JSONObject jsonObject = new JSONObject(rewardJson);
boolean filed = jsonObject.getBoolean("filed"); //獲得配置引數
JSONArray rewards = jsonObject.getJSONArray("rewards");//獲得獎品列表
//獲得序列化的獎品集合
ArrayList<Reward> list = new ArrayList<>();
//遍歷jsonArray,將每個JsonObject轉換為對應的Reward物件
for (int i = 0, length = rewards.length(); i < length; i++) {
JSONObject o = rewards.getJSONObject(i);
Reward reward = new Reward(o.getString("name"),
Float.parseFloat(String.valueOf(o.getString("probability"))),
o.getInt("image_res"),
o.getString("reward_serial")
);
probability += reward.probability;
list.add(reward);
}
//接下來就可以處理這些物件了(比如操作資料庫,比如通過概率進行抽獎等等)~