Home > Net >  Read from json file into IEnumerable using System.Text.Json
Read from json file into IEnumerable using System.Text.Json

Time:11-26

I've a problem by reading from a json to a IEnumerable in C# with System.Text.Json...

That's the error:

System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.Dictionary`2[System.String,System.String[]]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

The following lines contain my code:

private static Dictionary<string, string[]>? GetStaticMedicalAdvisors()
        {
            // TODO - read from json
            // TODO - convert to contact
            // TODO - add contacts to list
            // TODO - DO NOT USE NEWTONSOFT.JSON (use System.Text.Json)
            // TODO - return list

            var json = System.IO.File.ReadAllText("MedicalAdvisors.json");
            var dict = JsonSerializer.Deserialize<Dictionary<string, String[]>>(json);

            return dict;
        }  

This is my MedicalAdvisors.json:

[
  {
    "name": "Franz Immer",
    "endpoint": "000",
    "country": "CH"
  },
  {
    "name": "Nathalie Krügel",
    "endpoint": "000",
    "country": "CH"
  }
]

CodePudding user response:

Your json will deserialize as:
var result = JsonSerializer.Deserialize<Dictionary<string,string>[]>(json);

However, wouldn't it be more useful to create a Type that matches the structure?

public class UserInfo
{
    public string name { get; set; }
    public string endpoint { get; set; }
    public string country { get; set; }
}

var result = JsonSerializer.Deserialize<UserInfo[]>(json);

CodePudding user response:

You need to deserialize the json data according to the Model structure. NewtonSoft has a solution for deserialize.

  • Related