我有一个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字符串
Gson gson = new Gson();
String chequeInput = gson.toJson(criteria);
System.out.println("JSON String: " + chequeInput);
最佳答案
如果您在每个所需字段的集合或数组中都有不同的对象,则只会出现响应。一个类的每次获取都将以逗号分隔,括号将在可迭代项中仅出现两个不同的位置。我认为如果使用HashMap,您可能会得到想要的东西。但是寻找更好。
关于java - 使用gson获取正确的JSON字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44263551/