[英]How to add object to JSONArray
我想将一个对象添加到数组中。 如果other_amount
的数据大于零,我想再添加一个对象。 如果它等于零,它应该什么都不加。 这是我的代码:
JSONArray acc_data = new JSONArray();
Map<String, Object> myaccount = new LinkedHashMap<>();
for (int i = 0; i < mpay.size(); i++) {
if(other_amount>0){
myaccount.put("poAccount", other_account);
myaccount.put("poAmount", other_amount);
system.out.println(myaccount);
//{poAccount=050017, poAmount=12}
}
myaccount.put("poAccount", amount_account);
myaccount.put("poAmount", amount);
system.out.println(myaccount);
//{"poAccount":"050016","poAmount":"800"}
acc_data.add(myaccount);
system.out.println(acc_data);
//[{"poAccount":"050016","poAmount":"800"}]
}
但我需要这样:
//[{"poAccount":"050016","poAmount":"800"},{poAccount=050017, poAmount=12}]
请帮我解决它。
您不应该在您的情况下使用地图。 当您将现有的对放在映射键中时,该对将被覆盖。 例如
map.put ("k1","v1");
映射包含一对 "k1":"v1" 下一个调用
map.put ("k1","newV1");
第一对将被覆盖,地图仍然包含一对:“k1”:“newV1”
对于您的情况,最好使用 2 个字段poAccount
和poAmount
定义简单的 POJO 类。 并将它们添加到 JSONArray
您遵循的方法将无法满足您的要求。 您应该使用 pojo 来存储记录,然后填充 Json 数组。 您可以查看此代码并根据您的要求进行修改。
public class Test {
public static void main(String[] args) {
Mypojo mypojo = new Mypojo();
Gson gson = new Gson();
JSONArray records = new JSONArray();
for (int i = 0; i < 1; i++) {
if (5 > 0) {
mypojo.setPoAccount("050017");
mypojo.setPoAmount("12");
JSONObject objects = new JSONObject(gson.toJson(mypojo));
records.put(objects);
}
mypojo.setPoAccount("050016");
mypojo.setPoAmount("800");
JSONObject objects = new JSONObject(gson.toJson(mypojo));
records.put(objects);
}
System.out.println(records);
}
}
Mypojo类:
public class Mypojo
{
private String poAmount;
private String poAccount;
public String getPoAmount ()
{
return poAmount;
}
public void setPoAmount (String poAmount)
{
this.poAmount = poAmount;
}
public String getPoAccount ()
{
return poAccount;
}
public void setPoAccount (String poAccount)
{
this.poAccount = poAccount;
}
@Override
public String toString()
{
return "ClassPojo [poAmount = "+poAmount+", poAccount = "+poAccount+"]";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.