java操作json数据之net.sf.json-lib( 二 )


import java.util.List;
4.2 关头代码:
public static void testList(){    
//将调集对象转为json对象 , json字符串    
List<Student> list= new ArrayList<Student>();    
Student st = new Student();    
st.setId(1);    
st.setName("张三");    
st.setSex("男");    
Student st2 = new Student();    
st2.setId(2);    
st2.setName("小丽");    
st2.setSex("女");    
list.add(st);   
list.add(st2);    
//将类转为json对象    
JSONArray array=JSONArray.fromObject(list);    
System.out.println(array.toString());    
【java操作json数据之net.sf.json-lib】//将json对象转为对应的调集类    
JSONArray arrayBean = JSONArray.fromObject(array.toString());    
List<Student> listBean = (List<Student>) JSONArray.toCollection(arrayBean,Student.class);    
//输出转换后的成果    
for (Student lst: listBean) {        
System.out.println("name:"+lst.getName());    
}
}

java操作json数据之net.sf.json-lib



java操作json数据之net.sf.json-lib



5第五
:多层实体类处置 。
1、实体类:set和get方式本身生当作(set和get方式必需有)
public class Person     private String id;    private Person pserson;
}
2、关头测试代码:实体类Person 属性仍是Person 时json解析为实体类时一次搞定 。
import net.sf.json.JSONObject;
public static void main(String[] args) {    Person p1 = new Person();    p1.setId("111");    Person p2 = new Person();    p2.setId("222");    Person p3 = new Person();    p3.setId("333");    p1.setPserson(p2);    p2.setPserson(p3);    JSONObject jsonp = JSONObject.fromObject(p1);    System.out.println(jsonp);    Object objp = JSONObject.toBean(jsonp,Person.class);    Person p4 = (Person) objp;    Person p5 =  p4.getPserson();    Person p6 =  p5.getPserson();    System.out.println(p6.getId());}
3、map属性中存放map时比力麻烦需要利用MorphDynaBean 或者get一次解析一次 。
public static void main(String[] args) {    Map map1 = new HashMap();    Map map2 = new HashMap();    Map map3 = new HashMap();    map3.put("value","Male");    map2.put("ger",map3);    map1.put("attributes",map2);    JSONObject json = JSONObject.fromObject(map1);    System.out.println(json);    Object obj2 = JSONObject.toBean(json,Map.class);    Map map = (Map) obj2;    MorphDynaBean map4 = (MorphDynaBean) map.get("attributes");    MorphDynaBean map5 = (MorphDynaBean) map4.get("ger");    String male = (String) map5.get("value");    System.out.println(male);    //或者利用get一次解析一次    JSONObject json3 = JSONObject.fromObject(json.get("attributes"));    Map map6 = (Map) JSONObject.toBean(json3,Map.class);    JSONObject json4 = JSONObject.fromObject(json3.get("ger"));    Map map7 = (Map) JSONObject.toBean(json4,Map.class);    System.out.println(map7.get("value"));}

java操作json数据之net.sf.json-lib

猜你喜欢