5

I am trying to add a JSONArray toa JSONObject using the code below:

   defObj.put("locArr",(Object)locArr);

But this is resulting in the following format of JSON:

   ["locArr":"[{"longitude":35,"latitude":39,"ip":"81.212.204.150"},
               {"longitude":-122.1781,"latitude":37.459,"ip":"173.252.110.27"}]"]

I am initializing and populating locArr as shown below:

   JSONObject locObj = new JSONObject();
   JSONArray locArr = new JSONArray();
   locObj.put("ip", ip);
   locObj.put("latitude", latitude);
   locObj.put("longitude", longitude);
       locArr.put(locObj)

As you can see the value of the JSONArray is being enclosed in double quotes. Because of this, when I am trying to parse this JSON, I am facing an Unexpected character error because of the quote.

I want the output like below:

   ["locArr":[{"longitude":35,"latitude":39,"ip":"81.212.204.150"},
               {"longitude":-122.1781,"latitude":37.459,"ip":"173.252.110.27"}]]

Could anyone please let me know how to add the value of JSONArray without enclosing with double quotes?

7
  • Can you show us how you initialize and populate locArr? Commented May 6, 2014 at 10:25
  • @AndrewShepherd I have updated the question. Please check Commented May 6, 2014 at 10:28
  • Where are you trying to parse JSON ? in javascript? Commented May 6, 2014 at 10:53
  • @pramod.nikam.dev I am trying to parse it in JAVA Commented May 6, 2014 at 10:54
  • Share how you want the output to look like. Do you mean you want to remove the quotes from "locArr"? Commented May 6, 2014 at 10:55

2 Answers 2

4

I think you need an enclosing JSON array :

JSONObject locObj = new JSONObject();
locObj.put("ip", ip);
locObj.put("latitude", latitude);
locObj.put("longitude", longitude);

// Inner array
JSONArray locArr = new JSONArray(); 
locArr.put("locArr", locObj);

// Parent array
JSONArray parentArr = new JSONArray();
parentArray.put(locArr);
Sign up to request clarification or add additional context in comments.

Comments

1

Try removing the object casting:

defObj.put("locArr", locArr);

Hope this helps.

2 Comments

I have tried this and it resulted in this format: "locArr":["[{"longitude":35,"latitude":39,"ip":"81.212.204.150"},{"longitude":35,"latitude":39,"ip":"212.156.101.117"}]"]
Please share the whole method body so I can run it locally and revert back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.