我想返回有效的json字符串。
例如:
{
"status":"Success",
"total_amt": "41",
"igst_amt": 14,
"sgst_amt": 0,
"cgst_amt": "12",
"cess_amt": 15
}
预期:
{
"status":"Success",
"total_amt": "41",
"igst_amt": "14",
"sgst_amt": "0",
"cgst_amt": "12",
"cess_amt": "15"
}
我写了下面的代码:
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt
+ "\",\"sgst_amt\":\"" + sgst_amt + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt + "\"}";
}
它没有返回有效的JSON。
答案 0 :(得分:1)
您可以使用第三方库。本示例使用GSON
class Result {
private String status;
@SerializedName("total_amt")
private int totalAmount;
@SerializedName("igst_amt")
private int igstAmount;
@SerializedName("sgst_amt")
private int sgstAmount;
@SerializedName("cgst_amt")
private int cgstAmount;
@SerializedName("cess_amt")
private int cessAmount;
public Result() {}
}
Result result = new Result();
// set your fields
String json = new Gson().toJson(result);
答案 1 :(得分:0)
阅读有关gson的信息,以返回json格式。 link to gson github
要简单使用它,您可以:
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String string = "you string";
return gson.toJson(string);
答案 2 :(得分:0)
我希望igst_amt,sgst_amt和cess_amt是整数。
因此您将.toString()添加到了它们
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt.toString()
+ "\",\"sgst_amt\":\"" + sgst_amt.toString() + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt.toString() + "\"}";
}