JohnDoe4136
JohnDoe4136

Reputation: 539

JSON result - JavaMe

I wish to get this as my json

{"image1.bmp": 
  {"description": "OK", "filename": "image1.bmp"}, 
{"image2.bmp": 
  {"description": "OK", "filename": "image2.bmp"}, 
{"image3.bmp": 
  {"description": "OK", "filename": "image3.bmp"}
}

but right now I am getting this instead

{"image1.bmp": 
  {"description": "OK", "filename": "image1.bmp"}
} 
{"image2.bmp": 
  {"description": "OK", "filename": "image2.bmp"}
} 
{"image3.bmp": 
  {"description": "OK", "filename": "image3.bmp"}
}

This is the code I have for JSON so far

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

And

toJSON(outer,"description:" + e.toString(), "filename:" + imageName);       
out.write(outer.toString().getBytes())

Upvotes: 2

Views: 252

Answers (1)

esaj
esaj

Reputation: 16035

The objects in the output you want aren't valid JSON, unless you put a } at the end of each object. Also, it looks like you want to add the images into an array, in JSON the arrays are between [ and ].

Simple solution: put each "outer"-JSONObjects to JSONArray and then call the arrays' 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(); }
    }

}

Output (formatted):

[
   {
      "image1.bmp":{
         "description":"Ok",
         "filename":"image1.bmp"
      }
   },
   {
      "image2.bmp":{
         "description":"Ok",
         "filename":"image2.bmp"
      }
   },
   {
      "image3.bmp":{
         "description":"Ok",
         "filename":"image3.bmp"
      }
   }
]

There are also many JSON-formatters and validators floating around the net, which can come pretty handy once your JSON-strings are 10000+ characters long and contain deep nesting.

Upvotes: 2

Related Questions