0

我可以使用以下代码解析简单的 JSON 字符串

HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
            URL.toString() );




    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));

            finalResult.setText("Done") ;

            Result = reader.readLine();


        } else {
             Result = "error";
        }
    } catch (ClientProtocolException e) {
         Result = "error";
        e.printStackTrace();
    } catch (IOException e) {
         Result = "error";
        e.printStackTrace();
    }

但现在我有以下 JSON 字符串

[{"Name":"Ali" ,"Age":35,"Address":"cccccccccccc"} ,{"Name":"Ali1" ,"Age":351,"Address":"cccccccccccc1"} ,
{"Name":"Ali2" ,"Age":352,"Address":"cccccccccccc2"}
]

和阶级代表它

package com.appnetics;

import android.R.string;

public class Encounter {
    public string Name;
    public string Address;
    public int Age;
}

我想遍历这个 JSON 并将其转换为list<Encounter>

任何想法如何做到这一点

4

2 回答 2

4

另一种更简单的方法是使用Gson 另一个库来简化您的实现,与 Android 平台附带的 org.json 实现相比,它更易于使用。

如果你对域对象没问题。然后你只有两行代码来解析 json ......就像

Gson gson = new Gson();
YourDomainObject obj2 = (YourDomainObject) gson.fromJson(jsonString,
   YourDomainObject.class);

它也可以处理集合 n 。

于 2012-06-10T08:31:33.620 回答
3

使用org.json命名空间。对于您的具体示例,您可以执行以下操作:

ArrayList<Encounter> encounters=new ArrayList<Encounter>();
JSONArray array=new JSONArray(Result);
for(int i=0;i<array.length();i++){
    JSONObject elem=(JSONObject)array.get(i);
    Encounter encounter=new Encounter();
    Encounter.Name=elem.getString("Name");
    Encounter.Age=elem.getInt("Age");
    Encounter.Address=elem.getString("Address");
    encounters.add(encounter);
}
于 2012-06-10T08:24:51.263 回答