【问题标题】:Deserialize nested json to string property将嵌套的 json 反序列化为字符串属性
【发布时间】:2018-09-03 03:12:13
【问题描述】:

我有一个包含嵌套 json 的 json 文件,我想在配置绑定时将其反序列化为字符串属性。

这是配置文件:

{
  "Service": {
    "Id": "ccApiMicroservice",
    "Configuration": {
      "Option1": "value1",
      "Option1": "value2"
    }
  }
}

这是对应的配置类:

public class ServiceOptions
{
    public string Id { get; set; }

    [JsonConverter(typeof(JsonStringConverter))]
    public string Configuration { get; set; }
}

我尝试使用自定义 json 转换器将嵌套的 json 转换为字符串,但是该转换器被绑定机制忽略(在转换器的方法中有断点,但没有一个被命中),即使我已经配置了它在 ConfigureServices 中像这样:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(
            options => options.SerializerSettings.Converters.Add(new JsonStringConverter()));

    services.Configure<ServiceOptions>(this.Configuration.GetSection("Service"));
}

我错过了什么?为什么转换器被忽略?还是有另一种方法如何将嵌套的 json 反序列化为字符串属性?

编辑

我尝试使用自定义 JSON 转换器的原因是,如果我尝试在应用程序的任何位置访问 ServiceOptions 实例,我会收到以下异常:

System.InvalidOperationException: 'Cannot create instance of type 'System.String' because it is missing a public parameterless constructor.'

【问题讨论】:

  • 我当然使用 Newtonsoft JSON,因为它是 ASP .NET 核心使用的默认序列化程序。问题是,如果我使用以下行将ServiceOptions 配置类绑定到 JSON:services.Configure&lt;ServiceOptions&gt;(this.Configuration.GetSection("Service"));,我会得到以下异常:System.InvalidOperationException: 'Cannot create instance of type 'System.String' because it is missing a public parameterless constructor.'。这就是我尝试使用自定义 JSONConverter 的原因。但是转换器被忽略了,我仍然得到异常。

标签: c# json asp.net-core


【解决方案1】:

以下是获取和解析 json 项的一种可能更简单的方法示例:

JObject config = JObject.Parse(File.ReadAllText("config.json"));
string service_id = (string)config.SelectToken("Service").SelectToken("Id");
Console.WriteLine(service_id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-11
    • 2022-01-20
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多