2013-02-12 26 views
0

我想使用json.org的JSONArray對象構造函數將java bean列表轉換爲JSON字符串。與包含列表的豆列表使用JSONArray

這裏是bean:

package jackiesdogs.bean; 

import java.util.*; 

public class UploadLog { 
    private String logDescription; 
    private List<String> headings; 
    private List<List<String>> log; 

    public UploadLog(String logDescription, List<String> headings, List<List<String>> log) { 
     this.logDescription = logDescription; 
     this.headings = headings; 
     this.log = log; 
    } 

    public String getLogDescription() { 
     return logDescription; 
    } 

    public void setLogDescription(String logDescription) { 
     this.logDescription = logDescription; 
    } 

    public List<String> getHeadings() { 
     return headings; 
    } 

    public void setHeadings(List<String> headings) { 
     this.headings = headings; 
    } 

    public List<List<String>> getLog() { 
     return log; 
    } 

    public void setLog(List<List<String>> log) { 
     this.log = log; 
    } 

} 

這裏是我使用的將其轉換爲JSON代碼:

JSONArray outputJSON = new JSONArray(output,false); 

我希望得到如下:

[{"headings":[{"Vendor Order Id"}],"logDescription":"You are attempting to upload a duplicate order.","log":[{[{"132709B"}]}]}] 

但是我得到:

[{"headings":[{"bytes":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}],"empty":false}],"logDescription":"You are attempting to upload a duplicate order.","log":[{}]}] 

任何想法?

+0

如何'output'聲明?它是如何填充的? – 2013-02-12 19:43:47

回答

0

我只對GSON很熟悉,這很可靠。以下內容適用於GSON。

import com.google.gson.Gson; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

public class PlayWithGson2 { 
    public static void main(String[] args) throws IOException { 
     PlayWithGson pwg = new PlayWithGson(); 

     List<String> headings = new ArrayList<String>(); 
     headings.add("Vendor Order Id"); 

     List<List<String>> log = new ArrayList<List<String>>(); 
     UploadLog ul = new UploadLog("headings", headings, log); 

     Gson gson = new Gson(); 
     String toJson = gson.toJson(ul); 
     System.out.println(toJson); 
    } 
} 

打印:

{"logDescription":"headings","headings":["Vendor Order Id"],"log":[]} 
+0

Perfecto!那就是訣竅。 – 2013-02-13 12:52:40