我尝试将JSONObject值放在JSONArray上的“for”指令中,并且第一个值组正确地工作,但是当我添加第二个值组时,我看到第一个值也被覆盖。我把代码和examepl更好地解释了。
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);
}
例如,我有这个值gruops:
在i = 0:
id:1 - calification:0 - 评论:“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)时,第一个值被第二个值覆盖,我该如何解决这个问题?谢谢!
答案 0 :(得分:3)
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);
}
答案 1 :(得分:0)
try
{
JSONObject js = new JSONObject();
JSONArray jsPoints = new JSONArray();
for(int i = 0; i < jsPoints.length; i++)
{
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);
}