/**
* <2> JSON-->JAVA
* 1.如果字段名有错无法匹配,会发出警告;属性得到是null.
* 2.转换:
* ->Object
* <1> 字符串封装成JSON 对象:【JSONObject.fromObject(jsonStr)】
* <2> JSON对象转换成Object:【(Address) JSONObject.toBean(jsonObject, Address.class)】
* ->Collection
* <1> 字符串封装成JSONArray 对象:【JSONArray.fromObject(jsonArrayStr)】
* <2> JSONArray对象转换成Java集合:【(List<Address>)JSONArray.toCollection(jsonArray, Address.class)】
*/
@Test
public void testJson2Java() throws InterruptedException {
// 1.JSON object
String jsonStr = "{\"city\":\"北京\",\"district\":\"清河\",\"street\":\"安宁庄东路南口\",\"no\":500}";
// 3.JSONArray
String jsonArrayStr = "[{\"city\":\"北京\",\"district\":\"清河\",\"street\":\"安宁庄东路南口\",\"no\":500},{\"city\":\"北京\",\"district\":\"上地\",\"street\":\"安宁庄东路\",\"no\":300}]";
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
JSONArray jsonArray = JSONArray.fromObject(jsonArrayStr);
// JSONObject.toBean(jasonObject,Class): Bean;
Address address = (Address) JSONObject.toBean(jsonObject, Address.class);
List<Address> list = (List<Address>)JSONArray.toCollection(jsonArray, Address.class);
// 1.输出Object
Thread.sleep(1000);
System.out.println("District:"+address.getDistrict());
// 2.输出Array
Thread.sleep(1000);
for(Address addr:list){
System.out.println(addr.getCity()+"\t"+addr.getDistrict()+"\t"+addr.getStreet()+"\t"+addr.getNo());
}
}
|