java中的java.lang.NullPointerException JSONObject数组

java中的java.lang.NullPointerException JSONObject数组,java,json,Java,Json,我刚刚开始使用java JSON库org.JSON.simple.JSONObject。 在我的代码中,我需要创建一个JSONObject的JSONARRAY, 但是,我没有在数组中找到3个不同的对象,而是找到了重复的最后一个对象 功能代码: 私有void setMesurementDate[]ts,整数[][]time,字符串mesurementLabel,对象[][]mesurementValue,整数[][]unit{ DateFormat DateFormat=new SimpleDa

我刚刚开始使用java JSON库org.JSON.simple.JSONObject。 在我的代码中,我需要创建一个JSONObject的JSONARRAY, 但是,我没有在数组中找到3个不同的对象,而是找到了重复的最后一个对象

功能代码:

私有void setMesurementDate[]ts,整数[][]time,字符串mesurementLabel,对象[][]mesurementValue,整数[][]unit{ DateFormat DateFormat=new SimpleDateFormatyyy MM dd'T'HH:MM:ss.SSSZ,Locale.FRENCH; JSONArray测量值=新JSONArray; JSONObject系列=新的JSONObject; JSONArray$\u时间=新JSONArray; JSONArray msrVal=新的JSONArray; JSONArray unitVal=新的JSONArray; JSONObject msr=新的JSONObject;
对于int i=0;i您不会为每次迭代创建新的JSON对象。您只会在开始时创建一个JSON对象,设置其值并将其添加到列表中。然后覆盖同一对象的值,并再次将其添加到列表中。最后,您将该对象添加到列表中三次,其值将是上次迭代的值

要解决此问题,请更改

JSONObject series = new JSONObject();
JSONArray $_time = new JSONArray();
JSONArray msrVal = new JSONArray();
JSONArray unitVal = new JSONArray();
JSONObject msr = new JSONObject();

for (int i=0; i<ts.length; i++) {
    $_time.clear();
    msrVal.clear();
    unitVal.clear();
    ...
    measurements.add(msr);
}


这样,您可以为每个步骤创建一个新对象,并避免更改以前的步骤。

您应该为JSON中的每个新对象重新初始化对象。Move JSONObject series=new JSONObject;JSONArray$\u time=new JSONArray;JSONArray msrVal=new JSONArray;JSONArray unitVal=new JSONArray;JSONObject msr=new JSONObject;在for循环中,你确定问题的标题吗?空指针发生在哪里?很抱歉,你是对的,我弄错了问题的标题,当前真正的问题是重复的输出,如描述中可能重复的。非常感谢,我不相信解决方案会这么简单就这样。
for (int i=0; i<ts.length; i++) {
    JSONObject series = new JSONObject();
    JSONArray $_time = new JSONArray();
    JSONArray msrVal = new JSONArray();
    JSONArray unitVal = new JSONArray();
    JSONObject msr = new JSONObject();
    ...
    measurements.add(msr);
}