Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON parsing in c# item is not an array

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!

like image 503
Swurderer Avatar asked Nov 06 '17 10:11

Swurderer


2 Answers

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"];
like image 140
Rohit Kumar Avatar answered Oct 18 '22 08:10

Rohit Kumar


 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());
         }
     }
 }
like image 21
Prasanka Samarawickrama Avatar answered Oct 18 '22 10:10

Prasanka Samarawickrama