如何在android中读取这个json?我对jsonobject和json字符串感到困惑

时间:2016-10-21 13:45:07

标签: android json android-json

我对JSON对象是什么以及JSON字符串是什么感到困惑。哪个部分是JSON对象,哪个是JSON字符串?

JSON示例1:

{ 
    "abc":"v1",
    "def":"v2"
}

JSON示例2:

{
    "res":"false",
    "error":{
        "code":101
    }
}

5 个答案:

答案 0 :(得分:0)

数据以名称/值对表示。

"abc":"v1"

大括号持有对象,每个名称后跟':'(冒号),名称/值对用(逗号)分隔。

{ 
"abc":"v1",
"def":"v2"
}

代码示例:

JSONObject obj = new JSONObject(jsonStr);
String abc = obj.get("abc");

方括号包含数组,值以(逗号)分隔。

{
   "books": [

      {
         "id":"01",
         "language": "Java",
         "edition": "third",
         "author": "Herbert Schildt",
      },

      {
         "id":"07",
         "language": "C++",
         "edition": "second",
         "author": "E.Balagurusamy",
      }

   ]
}

代码示例:

JSONArray arrBooks = new JSONArray("books");
for (int i = 0; i<=arrBooks.length(); i++){
      JSONObject objBook = arrBooks.getJSONObject(i);
      String id = c.getString("id");
}

答案 1 :(得分:0)

由你的第一个例子给出:

try {
    JSONObject obj = new JSONObject(json);
    String abc = obj.get("abc");
    String def = obj.get("def");
} catch (Throwable t) {
    // Log something maybe?
}

答案 2 :(得分:0)

只需在构造函数中创建一个带有该字符串的JSONObject。

JSONObject obj = new JSONObject(your_string_goes_here);

您的JSON字符串是您看到的整个可视化表示形式(编码为字符串):

{ 
    "abc":"v1",
    "def":"v2"
}

您可以通过查找左括号{和结束括号&#39;}来确定特定JSON对象在字符串中的开始和结束位置。

在您的示例中,这是一个JSON对象:

{ 
    "abc":"v1",
    "def":"v2"
}

这就是:

{
    "res":"false",
    "error": {
        "code":101
    }
}

而且:

{
    "code":101
}

答案 3 :(得分:0)

使用GSON进行解析&amp;下面是json1&amp;的模型类。 json2

public class Json1 {


    /**
     * abc : v1
     * def : v2
     */

    private String abc;
    private String def;

    public String getAbc() {
        return abc;
    }

    public void setAbc(String abc) {
        this.abc = abc;
    }

    public String getDef() {
        return def;
    }

    public void setDef(String def) {
        this.def = def;
    }
}

Json2

public class Json2 {

    /**
     * res : false
     * error : {"code":101}
     */

    private String res;
    /**
     * code : 101
     */

    private ErrorBean error;

    public String getRes() {
        return res;
    }

    public void setRes(String res) {
        this.res = res;
    }

    public ErrorBean getError() {
        return error;
    }

    public void setError(ErrorBean error) {
        this.error = error;
    }

    public static class ErrorBean {
        private int code;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }
    }
}

我使用GsonFormatter插件创建模型类,使用Gson,它非常简单,你不需要解析任何东西

答案 4 :(得分:0)

JSON包含JSONObject&amp; JSONArray。 Json-1是JSONObject,而JSON -2也是JSONObject,其中包含另一个带有键"error"的JSONObject.JSON String是JSONObject的字符串表示形式,您可以通过JSONObject jsonObject = new JSONObject(); String jsonString = jsonObject.toString();