2016-08-21 68 views
0

我有一個自定義對象的ArrayList。每個這些對象都有另一個自定義對象的數組列表。然後這些自定義對象的第二級具有另一個自定義對象的陣列列表。將自定義對象的ArrayList轉換爲JSON

這是類層次的樣子

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); 

但似乎他們一個字符串的ArrayList只傳遞工作。

+0

試試這個:https://github.com/google/gson – Riad

+0

這將是有用的知道爲什麼問題已被downvoted – swati

回答

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); 
      }