illeb
illeb

Reputation: 2947

Error Parsing JSON,but code seems Ok

First of all,thanks for reading my question.

i have the following Json as a result of a web request.

{"GetCommunicationsResult":"
   {\"Rows\":
      [{\"Data\":\"2011-12-16T00:00:00\",\"Teacher\":\"Surname Name\",
       \"Communication\":\"bla bla bla and bla bla bla\"},

       {\"Data\":\"2011-10-18T00:00:00\",\"Teacher\":\"Surname Name\",
        \"Communication\":\"bla bla bla and bla bla bla\"}]
   }"
 }

I need to decode it in order to use my program.

  1. Firstly, i grab the JSON as a string resource

    JSONObject jsonData = readUrl("http://myWebSite/folder/site.svc/Communications/000884");
    

    (readurl is a method that returns the json as a string)

  2. Then i create a JSONObject by the use of this string

    JSONObject BaseObject = new JSONObject(jsonData);   
    

    (strangely,the JSONObject constructor doesn't provide any Inputstream or Reader parameter,but only strings or similar)

  3. Finally,i try to reduce my JSON

    JSONObject DerivatedObject=BaseObject.getJSONObject("GetCommunicationsResult");
    

But i encounter a strange exception:

Value {"Rows":[{"Data":"2011-12-16T00:00:00","Teacher":"Surname Name","Communication":"bla bla bla and bla bla bla"},{"Data":"2011-10-18T00:00:00","Teacher":"Surname Name","Communication":"bla bla bla and bla bla bla"}]} 
at GetCommunicationsResult of type java.lang.String cannot be converted to JSONObject

Any suggestion on how to solve this problem?
I cannot find out why my code actually finds the JSON but it can't decode it.

Upvotes: 0

Views: 130

Answers (1)

chubbsondubs
chubbsondubs

Reputation: 38686

You have an errant quote. See the last open quote on this line:

{"GetCommunicationsResult":"

That's causing the value to be a string and not a JSONObject. You can tell it's a string because all other "'s are escaped in the JSON:

{\"Rows\":

That should be;

{"Rows":

So something is wrong on the server that's causing that problem. Maybe you are putting something like this:

jsonObject.put("GetCommunicationsResult", someJsonObject.toString() );

Upvotes: 4

Related Questions