0

我有一个像

{ "1": "AAAA", "2": "BBBB","3":"CCCC","4":"DDDD","5":"EEEE"}

它由 c# 字典构造并发送响应到 android 客户端。而且我正在像java一样上课

public class Customer {

    int customerId;
    String customerName;
}

如何在java中解析或分配json值给这个类

4

1 回答 1

0

这将完成这项工作:

String json = "{ \"1\" : \"AAA\", \"2\" : \"BBB\" }";
JSONObject object = null;
try {
    object = new JSONObject(json);
} catch (JSONException e1) {
    e1.printStackTrace();
}
Iterator<String> i = (Iterator<String>)object.keys();
ArrayList<Customer> customers = new ArrayList<Customer>();
while(i.hasNext()) {
    String key = i.next();
    String name = null;
    try {
        name = object.getString(key);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Customer c = new Customer();
    c.customerId = Integer.parseInt(key);
    c.customerName = name;
    customers.add(c);
}
于 2013-06-25T10:31:22.177 回答