Jason文件解析

1.先从指定路径的文件里读取jason字符。

String fileStr = readFileString(filePath); ///filePath  /tranfs/CloudEngine/1008000035/tne.json

2. 把从文件里读取的string生成 JSONObject对象,然后再通过jason获取对应的key和值

JSONObject paramJsonObj = new JSONObject(fileStr);

3.数据解析

JSONObject的数据是用 { } 来表示的,

例如:

{
    "id":"1",
    "courseID":"化学",
    "title":"滴定实验",
    "content":"下周二实验楼201必须完成"
}
JSONObject表示一个JSON对象,包含一系列无序的键值对用于解析JSON对象数据,获取其中的值
JSONArray表示一个JSON数组,包含一系列JSON对象或值用于解析JSON数组数据,遍历数组中的每个对象

而JSONArray,顾名思义是由JSONObject构成的数组,用 [ { } , { } , … , { } ] 来表示

例如:



[
    {
        "id":"1",
        "courseID":"数学",
        "title":"一加一等于几"
    },
    {
        "id":"2",
        "courseID":"语文",
        "title":"请背诵全文"
    }
] 


表示了包含2个JSONObject的JSONArray。

可以看到一个很明显的区别,一个最外面用的是 { } ,一个最外面用的是 [ ] ;

3.1. 如何从字符串jsonString获得JSONObject对象和JSONArray对象
/*json字符串最外层是大括号时:*/
JSONObject jsonObject = new JSONObject(jsonStr);
/*json字符串最外层是方括号时:*/
JSONArray jsonArray = new JSONArray(jsonStr);

3.2. 如何从JSONArray中获得JSONObject对象
遇到方括号时,就要先获取JSONArray,然后再循环遍历出JSONObject

大家可以把JSONArray当成一般的数组来对待,只是获取的数据内数据的方法不一样。

 for (int i = 0; i < jsonArray.length(); i++) {

if( !jsonArray.isNull(j)){

  JSONObject jsonObject = jsonArray.getJSONObject(i);

}
 

3.3.数据解析:

在Java中,JSONObject类用于表示一个JSON对象,并提供了多种方法来获取其键对应的值。

获取值的方法
opt(String key):

根据键获取值,如果键不存在,则返回null。
推荐使用,因为不会抛出异常。
JSONObject jsonObject = new JSONObject("{\"name\":\"John\", \"age\":30}");
Object value = jsonObject.opt("name"); // 返回 "John"
Object missingValue = jsonObject.opt("nonexistent"); // 返回 null

get(String key):

根据键获取值,如果键不存在,则抛出JSONException。
JSONObject jsonObject = new JSONObject("{\"name\":\"John\", \"age\":30}");
Object value = jsonObject.get("name"); // 返回 "John"
Object missingValue = jsonObject.get("nonexistent"); // 抛出 JSONException

根据值的类型获取
optString(String key):

根据键获取字符串值,如果键不存在或值不是字符串,则返回空字符串或null。
String name = jsonObject.optString("name"); // 返回 "John"
String missingName = jsonObject.optString("nonexistent"); // 返回 ""

optInt(String key):

根据键获取整数值,如果键不存在或值不是整数,则返回0或指定的默认值。
int age = jsonObject.optInt("age"); // 返回 30
int missingAge = jsonObject.optInt("nonexistent", -1); // 返回 -1

optBoolean(String key):

根据键获取布尔值,如果键不存在或值不是布尔值,则返回false或指定的默认值。
boolean isMarried = jsonObject.optBoolean("married"); // 返回 true 或 false
boolean missingMarried = jsonObject.optBoolean("nonexistent", true); // 返回 true

optJSONObject(String key):

根据键获取JSONObject对象,如果键不存在或值不是JSONObject,则返回null。
JSONObject address = jsonObject.optJSONObject("address"); // 返回一个 JSONObject 对象或 null

optJSONArray(String key):

根据键获取JSONArray对象,如果键不存在或值不是JSONArray,则返回null。

    private String readFileString(String filePath) {
        String fileString = "";
        File file = new File(filePath);
        if(file.exists() && file.canRead()) {
            try(InputStreamReader in = new InputStreamReader(new FileInputStream(file));
                BufferedReader bf = new BufferedReader(in)) {
                StringBuffer buffer = new StringBuffer();
                String line = null;
                while (null != (line = bf.readLine())) {
                    buffer.append(line);
                }
                fileString = buffer.toString();
            } catch (Exception e) {
                Slog.e(TAG, "readFileString Error!" + e);
            }
        }else {
            Slog.d(TAG,"readFileString : File not exists or File can't Read ");
        }

        return fileString;
    }
  JSONObject paramJsonObj = new JSONObject(fileStr);
    
                if (paramJsonObj.has(CONFIG_ENABLE)) {
                    mEnable = paramJsonObj.optBoolean(CONFIG_ENABLE);
                }
                if (paramJsonObj.has(CONFIG_CONFIG)) {
                    JSONArray arr = paramJsonObj.optJSONArray(CONFIG_CONFIG);
                    if (arr != null && arr.length() > 0) {
                        mConfigInfos = new ArrayMap<>();
                        //遍历JSON数组得到其中的city数据
                        for (int i = 0; i < arr.length()-1; i++) {
                            JSONObject jObj = arr.getJSONObject(i);
                            logD("jObj = " + jObj );
                            String metric = jObj.optString(CONFIG_METRIC);
                            logD("metric = " + metric );
                            ConfigInfo info = new ConfigInfo(metric);

                            info.mEnable = jObj.optBoolean(CONFIG_ENABLE);
                            logD("mEnable = " +  info.mEnable );
                            info.mSamplingInterval = (jObj.optLong(CONFIG_SAMPLING_INTERVAL));
                            logD("mSamplingInterval = " +  info.mSamplingInterval  );
                            if(TextUtils.equals(metric,"startup")){
                                JSONArray jthld = jObj.getJSONArray(CONFIG_DEFAULT_THRESHOLD);
                                if (jthld != null && jthld.length() > 0){
                                    for (int k = 0; k < jthld.length(); k++) {
                                        JSONObject  threshold= jthld.getJSONObject(i);
                                        info.mDefaultThreshold.put(CONFIG_COLD, threshold.optLong(CONFIG_COLD));
                                        info.mDefaultThreshold.put(CONFIG_HOT, threshold.optLong(CONFIG_HOT));
                                        logD(" CONFIG_COLD = " + threshold.optLong(CONFIG_COLD));
                                    }
                                }

                            }else if(jObj.has(CONFIG_DEFAULT_THRESHOLD)){
                                info.mDefaultThreshold.put(CONFIG_DEFAULT_THRESHOLD, jObj.optLong(CONFIG_DEFAULT_THRESHOLD));
                                logD(" CONFIG_DEFAULT_THRESHOLD) = " + jObj.optLong(CONFIG_DEFAULT_THRESHOLD));
                            }

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值