将JSONArray与包含列表的bean列表一起使用

时间:2013-02-12 19:37:34

标签: java json javabeans arrays org.json

我正在尝试使用json.org的JSONArray对象构造函数将java bean的List转换为JSON字符串。

这是豆子:

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":[{}]}]

有什么想法吗?

1 个答案:

答案 0 :(得分: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":[]}