c#item中的JSON解析不是数组

时间:2017-11-06 10:37:37

标签: c# json json.net asp.net-core-2.0

我正在尝试解析JSON字符串,看起来像这样:

{
    "totalCreditsRemoved": 1,
    "invalidReceivers": [],
    "ids": [100070531],
    "validReceivers": ["+33635938286"]
}

我从Web API检索它,并将其存储为字符串:

var reader = new StreamReader(respStream);
String result = reader.ReadToEnd().Trim();
response = result;

响应是一个公共字符串

然后,在另一种方法中:我尝试解析我的json字符串:

var json = response;
var objects = JArray.Parse(json);

foreach (JObject root in objects)
{
    foreach (KeyValuePair<String, JToken> app in root)
    {
        totalCreditsRemoved = (String)app.Value["totalCreditsRemoved"];
        invalidReceivers = (String)app.Value["invalidReceivers"];
        ids = (String)app.Value["ids"];
        validReceivers = (String)app.Value["validReceivers"];
    }
}

但我总是得到这个错误:

  

JsonReaderException:从JsonReader读取JArray时出错。当前的JsonReader项不是数组:StartObject。路径&#39;&#39;,第1行,第1位。

此行发生错误:

var objects = JArray.Parse(json);

我不明白如何解决这个问题?不是OVHjson已经是一个阵列 提前谢谢!

2 个答案:

答案 0 :(得分:4)

不需要JArray.Parse,因为它不是一个数组..并且正在做一个矫枉过正......因为错误..

  

var objects = JObject.Parse(json);

将完成这项工作

并提取

totalCreditsRemoved = (String)objects.Value["totalCreditsRemoved"];
invalidReceivers = (String)objects.Value["invalidReceivers"];
ids = (String)objects.Value["ids"];
validReceivers = (String)objects.Value["validReceivers"];

答案 1 :(得分:0)

 dynamic jsonObj = JsonConvert.DeserializeObject(responseFromServer);
 foreach (var obj in obj1.Properties())
 {
     if (obj.Name == "rewardConfirmation") {
         foreach (var obj2 in obj.Value)
         {
             MessageBox.Show(obj2.ToString());
         }
     }
 }