我试图将String转换为Json Array(无名称/标签)并遍历结果数组。.但是,当我调试代码时,结果json数组显示为null。我找不到导致此问题的原因。
下面是我要解析为Json数组的给定字符串。
String jsonString="[ {"
+ "\"TimeStamp\": \"20:10\","
+ "\"PipeTemp\": \"31.5\","
+ "\"ChocolateMixingTemp\": \"25\","
+ "\"WaterCoolingTemp\": \"5\","
+ "\"WaterMixingTemp\": \"0\","
+ "\"WaterHeatingTemp\": \"0\",},
+{"
+ "\"TimeStamp\": \"20:00\","
+ "\"PipeTemp\": \"35.5\","
+ "\"ChocolateMixingTemp\": \"28\","
+ "\"WaterCoolingTemp\": \"3\","
+ "\"WaterMixingTemp\": \"15\","
+ "\"WaterHeatingTemp\": \"0\","
+}]";
我将上面的字符串传递给Java Array实例,然后使用for循环对其进行迭代以生成PDF表。但是当我尝试检查其大小时,我看到Json Array显示为null。
JSONArray jsonArray = new JSONArray(jsonString);
JSONObject jsonObject;
for(int n = 0; n < jsonArray.length(); n++)
{
table.addCell(createCell( (String) jsonObject.get("TimeStamp"),Element.ALIGN_CENTER));
table.addCell(createCell( (String) jsonObject.get("PipeTemp"),Element.ALIGN_CENTER));
table.addCell(createCell( (String) jsonObject.get("ChocolateMixingTemp"), Element.ALIGN_CENTER));
table.addCell(createCell( (String) jsonObject.get("WaterCoolingTemp"),Element.ALIGN_CENTER));
table.addCell(createCell( (String) jsonObject.get("WaterMixingTemp"),Element.ALIGN_CENTER));
jsonObject.get("WaterHeatingTemp"),Element.ALIGN_CENTER));
}
有人可以帮助我确定为什么数组显示为空吗? 我还尝试使用仅包含两个键值对的简单字符串进行测试。但是得到了相同的结果。
答案 0 :(得分:1)
您的代码错误。尝试以下代码来测试JSON数组:
String jsonString = "[ {"
+ "\"TimeStamp\": \"20:10\","
+ "\"PipeTemp\": \"31.5\","
+ "\"ChocolateMixingTemp\": \"25\","
+ "\"WaterCoolingTemp\": \"5\","
+ "\"WaterMixingTemp\": \"0\","
+ "\"WaterHeatingTemp\": \"0\",},"
+ "{"
+ "\"TimeStamp\": \"20:00\","
+ "\"PipeTemp\": \"35.5\","
+ "\"ChocolateMixingTemp\": \"28\","
+ "\"WaterCoolingTemp\": \"3\","
+ "\"WaterMixingTemp\": \"15\","
+ "\"WaterHeatingTemp\": \"0\","
+ "}]";
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println(jsonArray);
for (int n = 0; n < jsonArray.length(); n++) {
JSONObject jsonObject = jsonArray.getJSONObject(n);
System.out.println((String) jsonObject.get("TimeStamp"));
}
答案 1 :(得分:0)
首先,您的json字符串格式不正确,请参见以下格式:
String s="[ {"
+ "\"TimeStamp\": \"20:10\","
+ "\"PipeTemp\": \"31.5\","
+ "\"ChocolateMixingTemp\": \"25\","
+ "\"WaterCoolingTemp\": \"5\","
+ "\"WaterMixingTemp\": \"0\","
+ "\"WaterHeatingTemp\": \"0\",},"
+ "{"
+ "\"TimeStamp\": \"20:00\","
+ "\"PipeTemp\": \"35.5\","
+ "\"ChocolateMixingTemp\": \"28\","
+ "\"WaterCoolingTemp\": \"3\","
+ "\"WaterMixingTemp\": \"15\","
+ "\"WaterHeatingTemp\": \"0\","
+ "}]";
第二,我看不到您的jsonObject被初始化。 如果要使用json中的值,请使用jsonArray.get(index)方法。