gpt4 book ai didi

java - JSONObject 覆盖 JSONArray

转载 作者:行者123 更新时间:2023-11-29 05:24:32 31 4
gpt4 key购买 nike

我尝试将 JSONObject 值放在“for”指令的 JSONArray 上,并且第一个值组可以正常工作,但是当我添加第二个值组时,我发现第一个值也被覆盖了。我放了代码和一个例子来更好地解释它。

JSONArray jsPoints = new JSONArray();
JSONObject js = new JSONObject();
for(int i = 0; i < points.length; i++)
{
try
{
js.put("id",points[i]._id);
js.put("calification",points[i]._calification);
js.put("comment",points[i]._comment);
js.put("gps",points[i]._coords);
js.put("X",points[i]._X);
js.put("Y",points[i]._Y);
}
catch (JSONException e)
{
e.printStackTrace();
}
jsPoints.put(js);
}

例如,我有这个值组:

在 i = 0 时:

id: 1 - calification: 0 - comment: "hi"- gps: 0 - X: 220 - Y: 110

在 i = 1 时;

id: 2 - calification: 2 - comment: "hello"- gps: 40.324 - X: 10 - Y: 52

当我输入第一个值 (i = 0) 时,我正确地添加了 jsPoints,但是当我输入第二个值 (i = 1) 时,第一个值被第二个值覆盖,我该如何解决这个问题?谢谢!

最佳答案

JSONArray jsPoints = new JSONArray();

for(int i = 0; i < points.length; i++)
{
JSONObject js = null;

try
{
js = new JSONObject();
js.put("id",points[i]._id);
js.put("calification",points[i]._calification);
js.put("comment",points[i]._comment);
js.put("gps",points[i]._coords);
js.put("X",points[i]._X);
js.put("Y",points[i]._Y);
}
catch (JSONException e)
{
e.printStackTrace();
}
if(js!=null)
jsPoints.put(js);

关于java - JSONObject 覆盖 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23195880/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com