我根据文件中的用户输入生成了一个json字符串,如下所示
[{"id":1,"variableName":"x1","lowerInfinity":"false","upperInfinity":"true","type":"integer"},{"id":2,"variableName":"x2","lowerInfinity":"true","upperInfinity":"true","type":"integer"}]
我得到输入字符串并生成json字符串,如下所示
JSONArray JsonData = new JSONArray();
BufferedReader br = new BufferedReader(new FileReader("---");
while ((sCurrentLine = br.readLine()) != null) {
if(some condition)
JSONObject DataObj = new JSONObject();
DataObj.put("id","1");
....
...
}
JsonData.add(DataObj);
}
现在我不知道如何更新if循环之外的这个json对象的值。例如,如果我想添加一个新字段说
JSONArray JsonData = new JSONArray();
BufferedReader br = new BufferedReader(new FileReader("---");
while ((sCurrentLine = br.readLine()) != null) {
if(some condition)
JSONObject DataObj = new JSONObject();
DataObj.put("id","1");
....
...
}
DataObj.put("isActive","true");
JsonData.add(DataObj);
}
然后我得到输出字符串如下
[{"id":1,"variableName":"x1","lowerInfinity":"false","upperInfinity":"true","type":"integer"},{"id":2,"variableName":"x2","lowerInfinity":"true","upperInfinity":"true","type":"integer"},{"isActive":"true"}]
但我想让json字符串像
[{"id":1,"variableName":"x1","lowerInfinity":"false","upperInfinity":"true","type":"integer","isActive":"true"},{"id":2,"variableName":"x2","lowerInfinity":"true","upperInfinity":"true","type":"integer","isActive":"true"}]
即使我在while循环之后将json对象添加到json数组我也没有得到所需的输出。不确定我是否以错误的方式执行...任何帮助PLZ ....
答案 0 :(得分:0)
尝试在if条件
上方创建JSONObject DataObj = new JSONObject();
JSONArray JsonData = new JSONArray();
BufferedReader br = new BufferedReader(new FileReader("---");
while ((sCurrentLine = br.readLine()) != null) {
JSONObject DataObj = new JSONObject();
if(some condition)
DataObj.put("id","1");
....
...
}
DataObj.put("isActive","true");
JsonData.add(DataObj);
}