如何检查JSON中的值

时间:2017-07-16 08:34:29

标签: android json

我有这个JSON我希望检查此JSON有"song""fun"然后获取值和密钥"price"

{
    "has_error": false,
    "response": {
        "song": {
            "price": "2000"
        },
        "jok": {
            "price": "free_for_now"
        }
    },
    "state_code": 200
}

3 个答案:

答案 0 :(得分:4)

JSONObject类有 has 方法。

参考链接:http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

如果此对象具有名称的映射,则返回true。映射可能为NULL。

例如

if (json.has("song")) {
     JSONObject song = jsonObject.getJSONObject("song");
 }
 if (json.has("fun")) {
     JSONObject fun = jsonObject.getJSONObject("fun");
 }

答案 1 :(得分:1)

只使用gson,你必须做的是创建一个java类来映射你的json字符串。

yarn global add angular-cli

小心为每个属性和类名使用相同的名称,并生成getter和setter

然后您必须在gradle文件中使用导入GSON:

    class ModelObject{
        boolean has_error;
        Response response; // here you have the two objects: Song (with price attribute) and Jok (with price attribute); for these you must create another two classes 
        int status_code;
    }
    class Response{
        Song song;
        Jok jok;
    }

    class Song{
        String price;
    }

    class Jok{
        String price;
    }

最后,你唯一要做的就是使用gson中的方法:

compile 'com.google.code.gson:gson:2.2.4'

在obj中你有所有要处理的信息......

答案 2 :(得分:0)

使用此正确的工作

    JSONObject jsonObject = new JSONObject(response).getJSONObject("response");
          if (jsonObject.has("song")) {
            JSONObject song = jsonObject.getJSONObject("song");
}