且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安卓:JSON解析

更新时间:2021-08-07 22:34:43

您可以使用本网站格式化在你的JSON字符串中一个简单的方法来查看。
Android提供了一个适当的库做你想要的东西。

You can use this website to format your JSON string in a in an easier way to view it. Android provides an appropiate library to do what you want.

是你需要COM $手册页p $ phend如何使用Android JSON API。

This is the manual page you need to comprehend how to use Android JSON API.

这里你可以看到一个教程,理解如何解析JSON字符串。

And here you can see a tutorial to understand how to parse JSON string.

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

如果上面的例子是你的字符串,可以解析它传递给JSONObject的构造器:

If the example above is your string, you can parse it passing it to the JSONObject constructor:

String jsonString = "...."; // the above string
try {
    JSONObject obj = new JSONObject(jsonString);
} catch (JSONException e) {
    // This exception is thrown if jsonString is not correctly formatted
}

现在,如果你想获得的JSONObject标有GlossList,里面上面的字符串,你可以这样做:

Now, if you want to get the JSONObject labled "GlossList", inside the string above, you can do this:

JSONObject glossList = obj.getJSONObject("glossary").getJSONObject("GlossDiv").getJSONObject("GlossList");

也有另一种可能:你也可以得到一些JSONArray。在我们的例子中,数组GlossSeeAlso:

There is also another possibility: you can also obtain some JSONArray. In our example, the array GlossSeeAlso:

JSONArray glossSee = glossList.getJSONObject("GlossEntry").getJSONObject("GlossDef").getJSONArray("GlossSeeAlso");

要直接拿到这个数组的值,可以使用方法的getString(int i)以;如果数组的抗衡是一个JSONObject,你可以使用的方法 getJSONObject(int i)以。您也可以使用该方法的getString(串标贴),将直接获得一个JSONObject的字符串:

To get directly a value of this array, you can use the method getString(int i); if the contend of the array is a JSONObject, you can use the method getJSONObject(int i). You can also use the method getString(String lable) to get directly a string in a JSONObject:

String title = glossDive.getString("title");
String firstElement = glossSee.getString(0);