2011-02-08 19 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ではありません。 –

+0

私はそれをStringに変更しても、それはまだ同じjsonの結果です。 – JohnDoe4136

+2

作成しようとしているJSONは、その内容の一部として2つの追加オブジェクト(image2.bmpとimage3.bmp)を持つオブジェクト(image1.bmp)を表しているようです。それは本当にあなたが望むものですか?たぶん、あなたの目標が何であるかについて、より多くの情報を提供することができます。 –

答えて

2

出力のオブジェクトは、各オブジェクトの末尾に}を置かない限り、有効なJSONではありません。また、イメージを配列に追加するように見えますが、JSONでは配列は[と]の間にあります。

シンプルなソリューション:

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(); } 
    } 

} 

出力(フォーマット済み):配列toString()をJSONArrayにそれぞれの "外側" -JSONObjectsを配置し、呼び出す

[ 
    { 
     "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文字以上で深いネスティングを含んでいれば、かなり便利になることがあります。