Pasindu Lakshan
Pasindu Lakshan

Reputation: 100

How to parse a json file into a JsonArray object in C#

I need to parse a json file to a JsonArray object in C#.

[
  {
    "id": 1,
    "first_name": "LAkshan",
    "last_name": "Parcell",
   
  },
  {
    "id": 2,
    "first_name": "Lakshan",
    "last_name": "Clement",
   
  }
]

Json file's contains are like that. I need to get that data into a JsonArray object, not to specific object that created by me. When I try to do it like this

JsonArray list = JsonConvert.DeserializeObject<JsonArray>(File.ReadAllText(JsonFilePath));

It throws this error

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type System.Text.Json.Nodes.JsonArray. Path '', line 1, position 1.

       

Upvotes: 0

Views: 658

Answers (1)

CodingMytra
CodingMytra

Reputation: 2600

Do this if you want to use JsonArray

JsonArray list = JsonSerializer.Deserialize<JsonArray>(File.ReadAllText(JsonFilePath),
        new JsonSerializerOptions()
        {
            AllowTrailingCommas = true,
        });

Upvotes: 4

Related Questions