序列化为 JSON 时将字典中的值添加到对象的属性中



我有这个模型

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

Dictionary中的值来自我的数据库,因此它们不同于另一个对象。无论如何,我需要返回一个Json在特定的格式,以便被第三方网格理解。示例代码

    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和转换器,但我不能达到这个结果。

您需要为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; }
}

相关内容

  • 没有找到相关文章

最新更新