我希望将此作为我的json
{"image1.bmp":
{"description": "OK", "filename": "image1.bmp"},
{"image2.bmp":
{"description": "OK", "filename": "image2.bmp"},
{"image3.bmp":
{"description": "OK", "filename": "image3.bmp"}
}
但是现在我得到了这个
{"image1.bmp":
{"description": "OK", "filename": "image1.bmp"}
}
{"image2.bmp":
{"description": "OK", "filename": "image2.bmp"}
}
{"image3.bmp":
{"description": "OK", "filename": "image3.bmp"}
}
到目前为止,这是我对JSON的代码
public void toJSON(JSONObject outer,String description, String imageName)
{
JSONObject inner = new JSONObject();
try
{
outer.put(imageName, inner);
inner.put("description", description);
inner.put("filename", imageName);
}
catch (JSONException ex) { ex.printStackTrace(); }
}
和
toJSON(outer,"description:" + e.toString(), "filename:" + imageName);
out.write(outer.toString().getBytes())
答案 0 :(得分:2)
您想要的输出中的对象不是有效的JSON,除非您在每个对象的末尾放置一个}。此外,看起来您想要将图像添加到数组中,在JSON中,数组位于[和]之间。
简单的解决方案:将每个“外部”-JSONObjects放到JSONArray中,然后调用数组'toString():
public class JSONtest
{
@Test
public void test() throws JSONException
{
JSONArray array = new JSONArray();
JSONObject im = new JSONObject();
toJSON(im, "Ok", "image1.bmp");
array.put(im);
im = new JSONObject();
toJSON(im, "Ok", "image2.bmp");
array.put(im);
im = new JSONObject();
toJSON(im, "Ok", "image3.bmp");
array.put(im);
System.out.println(array.toString());
}
public void toJSON(JSONObject outer,String description, String imageName)
{
JSONObject inner = new JSONObject();
try
{
outer.put(imageName, inner);
inner.put("description", description);
inner.put("filename", imageName);
}
catch (JSONException ex) { ex.printStackTrace(); }
}
}
输出(格式化):
[
{
"image1.bmp":{
"description":"Ok",
"filename":"image1.bmp"
}
},
{
"image2.bmp":{
"description":"Ok",
"filename":"image2.bmp"
}
},
{
"image3.bmp":{
"description":"Ok",
"filename":"image3.bmp"
}
}
]
网上还有很多JSON-formatters and validators浮动,一旦你的JSON字符串长度超过10000个字符并且包含深层嵌套,它就会非常方便。