2011-02-08 90 views
2

我希望得到这是我的JSONJSON结果 - JAVAME

{"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()) 
+2

看看[http://www.json.org],你所描述的理想结果是无效的JSON,因为第一个`},`后面的表达式不是一个字符串,而是一个对象。 – 2011-02-08 01:59:19

回答

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个字符并包含深层嵌套,它可以非常方便。