如何将此JSON字符串转换为等效的类列表

时间:2012-06-10 08:14:23

标签: android json

我可以使用以下代码解析简单的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>

任何想法如何做到

2 个答案:

答案 0 :(得分:4)

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

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

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

它也可以处理集合。

答案 1 :(得分: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);
}