如何向 JSONArray 添加对象

问题描述 投票:0回答:2

我想将一个对象添加到数组中。如果

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}]

请帮我解决。

java json object arraylist arrayobject
2个回答
0
投票

您不应该在您的案例中使用地图。 当您将与现有的映射键配对时,该配对将被覆盖。 例如

map.put ("k1","v1");

Map 包含一对 "k1":"v1" 下一个电话

map.put ("k1","newV1");

第一对将被覆盖,map 仍包含 1 对:“k1”:“newV1”

对于您的情况,最好定义带有 2 个字段

poAccount
poAmount
的简单 POJO 类。并将它们添加到 JSONArray


0
投票

您所遵循的方法无法满足您的要求。您应该使用 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+"]";
}
}
© www.soinside.com 2019 - 2024. All rights reserved.