JSON parsing in c# item is not an array

北城以北 提交于 2019-12-10 16:05:50

问题


I am trying to parse a JSON string, that looks like that:

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

I retrieve this from a web API, and stock it as a String:

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

Response is a public string

Then, in another method: I try to parse my json string:

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"];
    }
}

But I always get this error:

JsonReaderException: Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.

The error occurs at this line:

var objects = JArray.Parse(json);

I don't understand how to fix this ? Isn't OVHjson already an array Thanks in advance!


回答1:


No need for JArray.Parse as it is not a array ..and is doing an overkill..hence the error..

var objects = JObject.Parse(json);

will do the job

and to extract

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



回答2:


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


来源:https://stackoverflow.com/questions/47134936/json-parsing-in-c-sharp-item-is-not-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!