简体   繁体   中英

Read from json file into IEnumerable using System.Text.Json

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"
  }
]

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM