2

我有这个模型

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

4

1 回答 1

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; }
}
于 2013-06-14T16:29:02.443 回答