【问题标题】:Adding values from a dictionary to the object's properties when serializing to JSON序列化为 JSON 时将字典中的值添加到对象的属性中
【发布时间】:2013-06-12 22:36:12
【问题描述】:

我有这个模型

public class DTO
{
    public int Id {get;set;}
    public string Name { get; set; }
    public string LastName { get; set; }

    public Dictionary<string, string> Items { get; set; }
}

字典中的值来自我的数据库,因此它们因一个对象而异。无论如何,我需要以特定格式返回一个 Json,以便第 3 方网格能够理解。 示例代码

    public ActionResult Index()
    {
        DTO dto = new DTO()
        {
            Id = 1 ,
            Name = "Employee1",
            LastName = "last name value",
            Items = new Dictionary<string, string>()
        };
        // properties .....
        dto.Items.Add("Variable 1" , "Value 1 Goes here");
        dto.Items.Add("Variable 2", "Value 2 Goes here");
        dto.Items.Add("Variable 3", "Value 3 Goes here");              

        return Json(dto, JsonRequestBehavior.AllowGet);            
    }

想要的 Json 应该是这样的

{"Id":1, "Name":"Employee1","LastName":"Last Name Value","Variable 1":"Value 1 Goes here","Variable 2":"Value 2 Goes here","Variable 3":"Value 3 Goes here"}

注意字典表示不能是数组,即将行转换为列。我已经尝试了很多使用 JsonWriter 和转换器,但我无法达到这个结果。

【问题讨论】:

    标签: asp.net-mvc json.net json


    【解决方案1】:

    您需要为DTO 类创建一个转换器,而不是为它的Items 属性创建一个转换器,因为您正在修改整个对象的表示。

    class DtoConverter : JsonConverter
    {
        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
        {
            var dto = (Dto)value;
            var jobj = JObject.FromObject(dto);
            foreach (var item in dto.Items)
                jobj[item.Key] = item.Value;
            jobj.WriteTo(writer);
        }
    
        public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    
        public override bool CanConvert (Type objectType)
        {
            return typeof(Dto).IsAssignableFrom(objectType);
        }
    }
    

    用法(注JsonIgnoreAttribute):

    class Program
    {
        private static void Main ()
        {
            var dto = new Dto {
                Id = 1, Name = "Employee1", LastName = "LastName1",
                Items = new Dictionary<string, string> {
                    { "Variable 1", "Value 1 Goes here" },
                    { "Variable 2", "Value 2 Goes here" },
                    { "Variable 3", "Value 3 Goes here" },
                }
            };
            Console.WriteLine(JsonConvert.SerializeObject(dto, new DtoConverter()));
            Console.ReadKey();
        }
    }
    
    class Dto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
    
        [JsonIgnore]
        public Dictionary<string, string> Items { get; set; }
    }
    

    【讨论】:

    • 谢谢你的回答,实际上返回的字符串不被视为 json 响应......它的字符串值看起来像 "{\"Name\":\"Employee1\",\"LastName\": \"LastName1\",\"Variable 1\":\"Value 1 Goes here\",\"Variable 2\":\"Value 2 Goes here\"} 如何从控制器将其作为 Json 返回
    • @Gerard 正如您用json.net 标记的问题,我希望您已经解决了这个问题。您需要配置 ASP.NET MVC 以使用 JSON.NET 和提供的参数(具体来说,使用此转换器)。见stackoverflow.com/questions/7109967/…。如果您不担心正确的 Content-Type,那么我想您可以像返回字符串一样返回结果(我不熟悉 ASP.NET,所以不要指望详细说明)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-09-21
    • 1970-01-01
    • 2013-07-09
    相关资源
    最近更新 更多