Home > Enterprise >  c# convert Object to Json and Parse
c# convert Object to Json and Parse

Time:02-02

I have the following situation and when I try to run I see this expection: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1

object test = "[{\"id\":566},\"createdOn\":\"2022-01-28\"}]";

JObject json = JObject.Parse(test.ToString());
string[] param = { json.SelectToken("id").ToString() };

What can I do to avoid this issue and fill "param" variable with 566?

CodePudding user response:

not valid json

 object test = "[{\"id\":566\"},\"createdOn\":\"2022-01-28\"}]"; //bad

 object test = "[{\"id\":566,\"createdOn\":\"2022-01-28\"}]";   // good

CodePudding user response:

your json has one {, but 2 }}, so remove one after 566, and you have JArray, not JObject, so use this code

    var jsonParsed = JArray.Parse(test);
    int id = (int) jsonParsed[0]["id"];
    int[] ids= jsonParsed.Select( p => (int) p["id"]).ToArray();
  •  Tags:  
  • Related