Search code examples
androidjsoncreation

Adding link to json object in android


 JSONArray albumarray=new JSONArray();
   JSONObject imgobj=new JSONObject();
    imgobj.put("thumb", filepath.get(i));
    imgobj.put("main", filepath.get(i));
    albumarray.put(imgobj);
    JSONObject albumjson=new JSONObject();
   albumjson.put(albumname,albumarray);

When I convert albumjson to string using

albumjson.toString()

I am getting output as below.

{\"test2\":\"[{\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\",\\\"main\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\"}]\"}

the correct format i need is

{"test2":[{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg"},{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg"}]}

How to replace additional slashes.


Solution

  • PLease use JSONObject.getString('keyName') method instead of toString()

    EDIT:

    You should first understand why those extra \\ are showing up.It is an escape character for ".Hence,it is very much required there and is a part of JSON encoding .Hence,one should always use the above method to get values of keys whenever needed.

    apart from that you can try :

    JSONObject.toString(4) where 4 is actually indent spaces and see whether it helps.Otherwise there's simply no other option than to replace those extra \\ like

    myJsonString.replaceAll("\\","");
    

    or

     myJsonString=myJsonString.replaceAll("\\\\",""); 
    

    SECOND EDIT:

    The string you are sending is perfect to send to any server.You need to decode that string at the server end to JSON and then utilise it.

    If you are using .NET you can see this. Or if you are on some other platform you need to find out how to decode to JSON on that platform.