简体   繁体   English

使用 System.Text.Json 从 json 文件读取到 IEnumerable

[英]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...我通过 System.Text.Json 从 json 读取到 C# 中的 IEnumerable 遇到问题...

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 :这是我的MedicalAdvisors.json

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

Your json will deserialize as:您的 json 将反序列化为:
var result = JsonSerializer.Deserialize<Dictionary<string,string>[]>(json);

However, wouldn't it be more useful to create a Type that matches the structure?但是,创建一个与结构匹配的 Type 不是更有用吗?

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.需要根据Model结构反序列化json数据。 NewtonSoft has a solution for deserialize. NewtonSoft 有一个反序列化的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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