将json对象绑定到字符串web api

时间:2016-05-17 13:26:34

标签: c# json asp.net-web-api

我将以下json发布到web.api:

{
    "tipoReporte":"039",
    "fecha":"20/05/2016",
    "datos":{
        "Prop1":"prop1",
        "Prop2":"prop2",
        "Prop3":"prop3",
        "Prop4":"prop4",
        "Prop5":"prop5",
        "Prop6":"prop6"
    },
    "usuarioID":2
}

我需要的是数据'在c#侧作为字符串变量。我无法做到这一点,因为当我调试后端时,我总是看到我的变量' Datos'填充空值。以下是模型。知道如何将json对象映射到字符串吗?感谢。

    public int Id { get; set; }
    public int TipoReporte { get; set; }
    public DateTime Fecha { get; set; }
    public string Datos { get; set; }
    public int UsuarioID { get; set; }
    public int Enviado { get; set; }

2 个答案:

答案 0 :(得分:1)

您可以使用Dictionary<TKey, TValue>。例如:

public class MyObject
{
    public int Id { get; set; }

    [JsonProperty("tipoReporte")]
    public int TipoReporte { get; set; }

    [JsonProperty("fecha")]
    public DateTime Fecha { get; set; }

    [JsonProperty("datos")]
    public Dictionary<string, string> Datos { get; set; }

    [JsonProperty("usuarioID")]
    public int UsuarioID { get; set; }

    public int Enviado { get; set; }
}

答案 1 :(得分:0)

如果您希望将数据作为字符串,只需将引号括在括号

之外
{
        "tipoReporte":"039",
        "fecha":"20/05/2016",
        "datos": '{"Prop1":"prop1","Prop2":"prop2","Prop3":"prop3","Prop4":"prop4","Prop5":"prop5 "Prop6":"prop6" }',
        "usuarioID":2
    }