使用gson获取正确的JSON字符串

时间:2017-05-30 13:23:53

标签: java json gson

我有一个java对象,我需要转换为JSON字符串以获得宁静的Web服务输入。

我得到的字符串

{"userInfo":[{"userRef":"dummydata","docView":"dummy"}],
"searchParams":[{"dd_company":"dummy","dd_acc":"6000000","dd_serial_no":"0000","fr_amount":17779.24,"fr_doc_date":"May 4, 2015 12:00:00 AM"}],
"resultFilter":[{"sortBy":"dd_doc_d","ascending":false,"resultStart":1,"resultCount":10}]}

它应该是什么样的(注意每个字段用大括号分隔,而不是上面例子中的逗号)

{"userInfo":[{"userRef":"dummydata"},
{"docView":"dummy"}],"searchParams":[{"dd_company":"dummy"},
{"dd_acc":"6000000"},{"dd_serial_no":"0000"},
{"fr_amount":17779.24},{"fr_doc_date":"May 4, 2015 12:00:00 AM"}],
"resultFilter":[{"sortBy":"dd_doc_d"},
{"ascending":false},{"resultStart":1},
{"resultCount":10}]}

基本上我需要在我的数组中用大括号分隔每个项目。

public class UserInfo implements Serializable {
private String userRef;
private String docView;

public String getUserRef() {
    return userRef;
}
public void setUserRef(String userRef) {
    this.userRef = userRef;
}
public String getDocView() {
    return docView;
}
public void setDocView(String docView) {
    this.docView = docView;
}

}

public class SearchParams implements Serializable{
private String cd_company;
private String fr_acc;
private String fr_serial_no;
private Double fr_amount;
private Date fr_doc_d;

public String getCd_company() {
    return cd_company;
}
public void setCd_company(String cd_company) {
    this.cd_company = cd_company;
}
public String getFr_acc() {
    return fr_acc;
}
public void setFr_acc(String fr_acc) {
    this.fr_acc = fr_acc;
}
public String getFr_serial_no() {
    return fr_serial_no;
}
public void setFr_serial_no(String fr_serial_no) {
    this.fr_serial_no = fr_serial_no;
}
public Double getFr_amount() {
    return fr_amount;
}
public void setFr_amount(Double fr_amount) {
    this.fr_amount = fr_amount;
}
public Date getFr_doc_d() {
    return fr_doc_d;
}
public void setFr_doc_d(Date fr_doc_d) {
    this.fr_doc_d = fr_doc_d;
}
}

public class ResultFilter implements Serializable{
private String sortBy;
private boolean ascending;
private int resultStart;
private int resultCount;

public String getSortBy() {
    return sortBy;
}
public void setSortBy(String sortBy) {
    this.sortBy = sortBy;
}
public boolean getAscending() {
    return ascending;
}
public void setAscending(boolean ascending) {
    this.ascending = ascending;
}
public int getResultStart() {
    return resultStart;
}
public void setResultStart(int resultStart) {
    this.resultStart = resultStart;
}
public int getResultCount() {
    return resultCount;
}
public void setResultCount(int resultCount) {
    this.resultCount = resultCount;
}
}

我创建了一个gson对象,如下所示,打印出JSON String

Gson gson = new Gson();
String chequeInput = gson.toJson(criteria);
System.out.println("JSON String: " + chequeInput);

1 个答案:

答案 0 :(得分:0)

如果您在集合或数组中为所需的每个字段都有不同的对象,则响应才会如此。每个类的获取将只用逗号分隔,并且括号将在可迭代项中出现两个独立的不同位置。我想如果你使用HashMap,你可能会得到你想要的东西。但要更好地寻找它。