0

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.

       
5
  • 4
    Do you want to use the Newtonsoft.Json APIs or the System.Text.Json APIs? Pick one. Commented Sep 2, 2022 at 7:34
  • Basically, if you're happy using Newtonsoft.Json, deserialize into JArray instead of JsonArray. Commented Sep 2, 2022 at 7:35
  • @sweeper Ok I need to get a System JsonArray object by that file. So is there any method to do that using System.Text.Json API? Commented Sep 2, 2022 at 7:36
  • @ Jon Skeet I need specifically a System JsonArray because it is needed to parse to another package (Fast report data souce) by JsonArray. Commented Sep 2, 2022 at 7:39
  • @PasinduLakshan you've mixed up different libraries. JsonConvert is a JSON.NET class while JsonArray is a System.Text.Json class. Use JsonSerializer.Deserialize if you want to use System.Text.Json Commented Sep 2, 2022 at 10:55

1 Answer 1

4

Do this if you want to use JsonArray

JsonArray list = JsonSerializer.Deserialize<JsonArray>(File.ReadAllText(JsonFilePath),
        new JsonSerializerOptions()
        {
            AllowTrailingCommas = true,
        });
Sign up to request clarification or add additional context in comments.

1 Comment

His json contains trailing commas so you need to add the corresponding option, otherwise this will throw an exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.