用Java解析XML,并转换为json格式(2)

原帖地址:http://www.2cto.com/kf/201402/279640.html

但是如果是两个model呢!因为我写的项目中就是需要用两个model获取!我先把我项目中从后台接收的xml列出来!


 
   true 
     
      0
       Normal
       正常
     
     
       0
       Normal
       暂停
     
 

要想解析这样的model需要用另外一种格式:

import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.ArrayList;
/**
 * 将model存在list集合中,并将集合转换为json格式
 * */
public class xmlJdom {
    public static void main(String[] args) {
        Student s1=new Student();
        s1.setAge(123);
        s1.setNameString(name);
        Student s2=new Student();
        s2.setAge(1234);
        s2.setNameString(what);
        Teacher teacher=new Teacher();
        teacher.setsAge(11);
        teacher.setsName(teacher);
        List lists=new ArrayList();
        lists.add(s1);
        lists.add(s2);
        teacher.setStudent(lists);
        new JSONObject();
        JSONObject jsonObject = JSONObject.fromObject(teacher); 
        System.out.println(jsonObject); 
        List list = new ArrayList();    
        list.add(s1); 
        list.add(s2);
        JSONArray jsonArr= JSONArray.fromObject(list); 
        System.out.println(jsonArr);
    }
}

输出的内容为:

{sAge:11,sName:teacher,student:[{age:123,nameString:name},{age:1234,nameString:what}]}
[{age:123,nameString:name},{age:1234,nameString:what}]

两个model:Student和Teacher

teacher里面包含student的list集合:

public class Student {  
   
    private String nameString;  
    private int age;  
     
    public String getNameString() {  
        return nameString;  
    }  
    public void setNameString(String nameString) {  
        this.nameString = nameString;  
    }  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
       
}

import java.util.List;
 
 
public class Teacher {
    private String sName;
    private int sAge;
    private List student;
    public List getStudent() {
        return student;
    }
    public void setStudent(List student) {
        this.student = student;
    }
    public String getsName() {
        return sName;
    }
    public void setsName(String sName) {
        this.sName = sName;
    }
    public int getsAge() {
        return sAge;
    }
    public void setsAge(int sAge) {
        this.sAge = sAge;
    }
}

这样就ok!现在已经学会了举一反三了!

 

如需转载请注明出处:Finder_畅畅

你可能感兴趣的:(java)