代码之家  ›  专栏  ›  技术社区  ›  Tropin Alexey Sam Fenilto

字典序列化:系统。例外:Type<Type>不是字典

  •  0
  • Tropin Alexey Sam Fenilto  · 技术社区  · 2 年前

    我有一本字典,我想把它作为控制器的输入:

    using Newtonsoft.Json;
    
    namespace LM.WebApp.Models.ApiModels;
    
    [JsonDictionary]
    public class Values
    {
        public Dictionary<string, string> values { get; set; }
    }
    
    public class Data
    {
        public bool is_active { get; set; }
        public IList<string> labels { get; set; }
        public string name { get; set; }
        public Values values { get; set; }
    }
    
    public class DictionaryImportApiModel
    {
        public IList<Data> data { get; set; }
    }
    

    我正在传递这个测试JSON的输入:

    {
      "data":
      [
        {
          "is_active": true,
          "labels": [
            "SYSTEM",
            "EXTERNAL"
          ],
          "name": "MEDICATION_REQUEST_INTENT",
          "values": {
            "order": "Замовлення ліків",
            "plan": "План застосування"
          }
        }
      ]
    }
    

    以及从入站对象中的问题标题和空字典中获取错误。我变了 Newtonsoft.Json 序列化程序 Microsoft.AspNetCore.Mvc.NewtonsoftJson 并删除属性 [JsonDictionary] 从…起 Values 类并添加 .AddNewtonsoftJson() 不久之后 AddControllersWithViews 在里面 Startup .Exception已消失,但入站对象中的字典仍为空。是否需要使用自定义转换器(如 this ) 处理字典?

    1 回复  |  直到 2 年前
        1
  •  2
  •   Guru Stron    2 年前

    改变 values 类型 Data 模仿 Dictionary<string, string> :

    public class Data
    {
        public bool is_active { get; set; }
        public IList<string> labels { get; set; }
        public string name { get; set; }
        public Dictionary<string, string> values { get; set; }
    }
    

    main支持的一种约定。NET json序列化程序(两者都是 Newtonsoft.Json System.Text.Json ,可能是其他人,但没有与他们合作)正在将json对象转换为 Dictionary ,所以不需要额外的包装器类 Values .

    附笔。

    除非在项目中有特定的命名约定,否则不需要像在源json中命名类属性那样命名类属性。对于 纽顿软件。Json 您可以使用 JsonPropertyAttribute 或者尝试设置相应的 NamingStrategy 在序列化程序设置中( 系统文本Json 有类似的选择)。