【问题标题】:How to parse json string in Android? [duplicate]如何在Android中解析json字符串? [复制]
【发布时间】:2011-12-26 19:46:08
【问题描述】:

可能重复:
JSON Array iteration in Android/Java

我正在从服务器获取 JSON 字符串,并且我已经通过代码获取了 JSON 字符串。 但是我不明白如何解析它。

下面是我的 JSON 字符串

{
    "university": {
        "name": "oxford",
        "url": "http://www.youtube.com"
    },
    "1": {
        "id": "2",
        "title": "Baseball",
        "datetime": "2011-11-11 10:41:46"
    },
    "2": {
        "id": "1",
        "title": "Two basketball team players earn all state honors",
        "datetime": "2011-11-11 10:40:57"
    }
}

请提供任何指导或代码sn-p。

【问题讨论】:

    标签: android json


    【解决方案1】:

    使用 JSON 类进行解析,例如

    JSONObject mainObject = new JSONObject(Your_Sring_data);
    JSONObject uniObject = mainObject.getJSONObject("university");
    String  uniName = uniObject.getString("name");
    String uniURL = uniObject.getString("url");
    
    JSONObject oneObject = mainObject.getJSONObject("1");
    String id = oneObject.getString("id");
    ....
    

    【讨论】:

    • 我们能得到json字符串中有多少个对象
    • 是的,你可以简单地使用“mainObject.length();”
    • 编辑为在获取字符串值时使用getString() 而不是getJSONObject()。当我运行使用 getString() 修复的类似代码时,使用 getJSONObject() 导致 JSONException。
    • getString(),而不是示例中所写的getJsonString(),对吧?
    • 正确@de。它应该是 getString(),而不是 getJsonString()
    【解决方案2】:

    以下是android中解析JSON字符串的指导链接。

    http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

    另外根据你的json字符串代码sn-p必须是这样的:-

    JSONObject mainObject = new JSONObject(yourstring);
    
    JSONObject universityObject = mainObject.getJSONObject("university");
    JSONString name = universityObject.getString("name");  
    JSONString url = universityObject.getString("url");
    

    以下是 JSOnObject 的 API 参考:https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

    其他对象也一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多