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

时间:2013-06-12 22:36:13

标签: asp.net-mvc json.net 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; }
}

词典中的值来自我的数据库,因此它们在一个对象之间存在差异。无论如何,我需要以特定格式返回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"}

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

1 个答案:

答案 0 :(得分: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; }
}