2014-02-07 51 views
-1

在我的Android项目,我有串text这得到了以下数据:解析JSON在Android和设置在ListView

[ 
    { 
    "admin": true, 
    "created_at": "2012-10-16T07:26:49Z", 
    "email": "[email protected]", 
    "id": 28, 
    "language": "fr", 
    "name": "Marc", 
    "profile_pic_content_type": null, 
    "profile_pic_file_name": null, 
    "profile_pic_file_size": null, 
    "profile_pic_updated_at": null, 
    "provider": null 
    }, 
    { 
    "admin": false, 
    "created_at": "2013-04-02T18:47:36Z", 
    "email": "[email protected]", 
    "id": 263, 
    "language": "en", 
    "name": "Marcus", 
    "profile_pic_content_type": null, 
    "profile_pic_file_name": null, 
    "profile_pic_file_size": null, 
    "profile_pic_updated_at": null, 
    "provider": null 
    } 
] 

我将它转换成JSON对象得益于此:

JSONObject jsonObj = new JSONObject(text); 

我想分析该Json对象,并将其设置在ListView中,但即使使用official documentation我也无法成功完成此操作。

解析后,我想只保留阵列的第一部分,并删除所有领域以外的电子邮件,语言和名称,到底得到这样的:

[ 
    { 
    "email": "[email protected]", 
    "language": "fr", 
    "name": "Marc" 
    } 
] 
+0

在json对象内部转换它,尝试解析它,然后将其转换为json对象作为字符串,但仍然没有成功 – sidney

+0

发布代码..相关片段 – Blackbelt

+0

您会笑我。 'Log.e(“retrieve2”,text.toCharArray()[0]);' – sidney

回答

2

你处理一个JSONArray - [] - 包含两个单独的JSONObject。从这个结构中提取数值的方式只是简单地逐一进行,首先从数组中获取嵌套对象,然后提取它们的内部值。你可以随意重新包装它。例如:

int numObject = jsonArray.length(); 
JSONArray repackArray = new JSONArray(); 
for(int i = 0; i < numObject; i++){ 
    JSONObject nested = jsonArray.getJsonObject(i); 

    //get values you need 
    String email = nested.getString("email"); 
    String language = nested.getString("language"); 
    String name = nested.getString("name"); 

    //add values to new object 
    JSONObject repack = new JSONObject(); 
    repack.put("email", email); 
    repack.put("language", language); 
    repack.name("name", name); 

    //add to new array 
    repackArray.put(repack); 
} 

另外,如果放不为你工作,你总是可以创建JSON格式的自己的字符串,然后简单地使用字符串作为构造函数的参数创建一个新的JSONObject。在上面的例子中,我假定你正在使用JSONArray。如果您从JSONObject开始,则过程是相同的。在开箱之前,先将JSONArray从对象中取出。

+0

感谢你的回答,我实现了它,但我得到了这个: '类型JSONArray中的方法getString(int)不适用于参数(String)'嵌套.getString“三行。 它期望一个索引,而不是一个字符串。我应该手动定义行号吗? – sidney

+0

获取字符串[不需要索引](http://developer.android.com/reference/org/json/JSONObject.html)。你得到这个错误是因为试图从'JSONArray'中获取一个字符串值。您只能从'JSONObject'中获取这些字符串值 - {}中的部分。我在上面提供的文本上根据该代码。如果实际的JSON格式不同 - 比如说包装在另一个“JSONObject”中的文本,则需要首先提取该数组,或在使用toJSONArray之前将其转换为“JSONArray”。 – Rarw

+0

谢谢你,它帮了很多 – sidney