C#字典json数据到java类对象
本文关键字:java 对象 数据 字典 json | 更新日期: 2023-09-27 18:19:44
我有一个类似的json数据
{ "1": "AAAA", "2": "BBBB","3":"CCCC","4":"DDDD","5":"EEEE"}
它由c字典构建,并向android客户端发送响应。我正在上类似的java课程
public class Customer {
int customerId;
String customerName;
}
如何在java中解析或分配json值
这将完成任务:
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);
}