无法解析JSON响应

时间:2016-08-31 16:18:09

标签: c# asp.net json asp.net-web-api json.net

我有一个发送JSON响应的服务。控制器方法如下所示:

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
}

获得响应的方法如下:

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
    }
}

无论在上面的控制器方法中选择了return语句,响应解析器在尝试解析响应时总是抛出错误。

将解析行更改为以下内容可以解决问题,但我不清楚为什么会这样。

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

另外,我想知道从ASP.NET web api2控制器发送JSON响应的正确方法是什么。我不想使用模型来创建响应,因为我有JSON字符串,我想直接返回而不是从中创建模型。

更新1: 错误如下:

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

2 个答案:

答案 0 :(得分:1)

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);

答案 1 :(得分:0)

这里的问题是控制器功能的返回类型。由于它是返回字符串,因此需要序列化为字符串才能获得正确的结果。返回JSON的正确方法是按照here的说明返回JToken。因此控制器需要更改为以下内容:

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