dknight
dknight

Reputation: 1243

Unable to Parse JSON Response

I have a service that sends JSON response. The controller method looks as follows:

string varStr = "{proper JSON here}";

public string GetListofResourcesInSubscription(string subscriptionId)
{
    // Uncomment any option below to test. The error persists either way.
    //return varStr;  --- Option 1
    return JsonConvert.SerializeObject(JObject.Parse(varStr)); // Option 2
}

The method that gets the response is like the following:

response = outgoingRequest.GetResponse() as HttpWebResponse;

if (response.StatusCode == HttpStatusCode.OK)
{
    responseStream = response.GetResponseStream();

    using (var reader = new StreamReader(responseStream))
    {
        string strResp = reader.ReadToEnd();
        JObject joResponse = JObject.Parse(strResp); // throws error
        JArray objArray = (JArray)joResponse["value"];
        // other processing
    }
}

Irrespective of the return statement selected in the controller method above, the response parser is always throwing an error while it is trying to parse the response.

Changing the parsing line to the following resolves the issue but it is not clear to me why it is so.

JObject joResponse = JObject.Parse(JsonConvert.DeserializeObject<string>(strResp));

Also, I want to know what is the correct way of sending a JSON response from an ASP.NET web api2 controller. I don't want to use models for creating the response because I have JSON strings that I want to return directly instead of creating models out of them.

Update 1: The error is the following:

   "Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 6546."}  System.Exception {Newtonsoft.Json.JsonReaderException}

Upvotes: 1

Views: 1022

Answers (2)

dknight
dknight

Reputation: 1243

The problem here was the return type of the controller function. As it was returning string, the serialization to string was required to get correct result. The correct way of returning JSON is to return a JToken as explained here. So the controller needs to be changed to the following:

   public JToken GetListofResourcesInSubscription(string subscriptionId)
   {
        return JObject.Parse(varStr);
   }

Upvotes: 0

Xavier J
Xavier J

Reputation: 4628

You can't deserialize a complex JSON object back to a string. Your example won't work, because you are assuming the JSON evaluates to a string:

JObject joResponse = JObject.Parse(JsonConvert.DeserializeObject<string>(strResp))

You might have more success either using a JObject, or the alternative is to deserialize into a Dictionary, or into a known type.

var dictionary = JsonConvert.DeserializeObject<<Dictionary<string,object>>(strResp);

Upvotes: 1

Related Questions