3

When i create a json object and add it to json array, it puts extra backslashes :/

1) Creating JSONObject

        JSONObject jo = new JSONObject();
        jo.put("JobName", "Test - Job Name");
        jo.put("JobStatus", "Current");
        jo.put("OrganID", "123");
        jo.put("Date_Entered", getDate());

Result:

{"OrganID":"123","JobName":"Test - Job Name","Date_Entered":"13-Apr-2015","JobStatus":"Current"}

2) Adding JSONObject to JSONArray

        JSONArray ja = new JSONArray();
        ja.put(jo);

Result (It also puts extra double quotes " before and after JSONObject):

["{\"OrganID\":\"123\",\"JobName\":\"Test - Job Name\",\"Date_Entered\":\"13-Apr-2015\",\"JobStatus\":\"Current\"}"]

3) Adding JSONArray to JSONObject

        JSONObject finalJson = new JSONObject();
        finalJson.put("PostCompJob", ja.toString());

Result:

{"PostCompJob":"[\"{\\\"OrganID\\\":\\\"123\\\",\\\"JobName\\\":\\\"Test - Job Name\\\",\\\"Date_Entered\\\":\\\"13-Apr-2015\\\",\\\"JobStatus\\\":\\\"Current\\\"}\"]"}  

I dont know why is this happening, can anyone please help me out?

Salmaan
  • 3,543
  • 8
  • 33
  • 59
  • I think When you add objects to array it always add slashes behind every string.. I am not sure. But why dont you use object instead of array ?? Try to make Json object on service side. wil def help you. – Ahmad Arslan Apr 13 '15 at 12:06
  • 1
    I can't reproduce your step 2. Using `System.out.println(ja);` I don't get any backslashes. Step 3 certainly *would* add backslashes, because you're trying to represent JSON as a string value *in JSON*. – Jon Skeet Apr 13 '15 at 12:06
  • Well i dont know why are backslashes being added, copied this code: http://stackoverflow.com/a/17810270/3828908 and still adds backslashes :/ what could be wrong @JonSkeet – Salmaan Apr 13 '15 at 12:10
  • Well you haven't told us how you're observing the backslashes. Could this just be an issue with viewing strings in a debugger? A short but complete program (outside Android, just as a console app) demonstrating the problem would go a long way. – Jon Skeet Apr 13 '15 at 12:14

1 Answers1

0

Oh Gosshh I have got the same issue But on my side it was due to AWS library. As I was using this Lib in my project and it automatically imports JSONObject or JSONArray of AWS lib whenever I have created this object. Slashes only created when I have created Json of AWS. If you are using some other library Please check first.

Ahmad Arslan
  • 4,498
  • 8
  • 38
  • 59