将自定义对象的ArrayList转换为JSON

时间:2016-08-21 06:10:03

标签: java json

我有一个自定义对象的ArrayList。这些对象中的每一个都具有另一个自定义对象的arraylist。然后,这些第二级自定义对象具有另一个自定义对象的arraylist。

这就是类层次结构的样子

public class Undle {
    private String undleStatus; 
    private ArrayList<ArcelFolder> arcelFolders;

    public ArrayList<ArcelFolder> getArcelFolders() {
        return arcelFolders;
    }
    public void setArcelFolders(ArrayList<ArcelFolder> arcelFolders) {
        this.arcelFolders = arcelFolders;
    }
    //Other getter and setters
}


public class ArcelFolder {
    private ArrayList<ArcelDocument> arcelDocuments;
    private String arcelStatus;
    public String getArcelStatus() {
        return arcelStatus;
    }
    public void setArcelStatus(String arcelStatus) {
        this.arcelStatus = arcelStatus;
    }
    public ArrayList<ArcelDocument> getArcelDocuments() {
        return arcelDocuments;
    }
    public void setArcelDocuments(ArrayList<ArcelDocument> arcelDocuments) {
        this.arcelDocuments = arcelDocuments;
    }
}

public class ArcelDocument {
    private String gain;

    public String getGain() {
        return gain;
    }
    public void setGain(String gain) {
        this.gain = gain;
    }
}

我有一个Undle对象的arraylist

ArrayList<Undle> undleList = new ArrayList<Undle>();
// Create objects of ArcelFolder and ArcelDocument
// Add ArcelDocument list to ArcelFolder
// Add ArcelFolder list to Undle arraylist

我想将Undle ArrayList转换为JSON。我怎样才能展平这种bean的层次结构并将其放入JSON中?

我尝试过像

这样的事情
org.json.simple.JSONObject resultObj = new JSONObject(undleList);

org.json.simple.JSONArray arr = new JSONArray(undleList);

但似乎它们仅在传递String ArrayList时才起作用。

1 个答案:

答案 0 :(得分:0)

Gson gson = new Gson();
             Type type = new TypeToken<List<Bundle>>() {}.getType();
             String json = gson.toJson(bundleList, type);
             System.out.println(json);
             List<Bundle> fromJson = gson.fromJson(json, type);

             for (Bundle bundle : fromJson) {
                     System.out.println(bundle);
             }