NicoRiff
NicoRiff

Reputation: 4883

bind json object to string web api

I'm posting the following json to the web.api:

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

What I need is that 'datos' is taken on the c# side as a string variable. I was not able to do that because when I debug the backend, I always see my variable 'Datos' filling with null value. Below is the model. Any idea of how I can map the json object to a string?. Thanks.

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

Upvotes: 0

Views: 560

Answers (2)

Nasreddine
Nasreddine

Reputation: 37838

You can use a Dictionary<TKey, TValue> for that. Example:

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

Upvotes: 1

fdfey
fdfey

Reputation: 587

If you want datos as a string just put quotes outside of brackets

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

Upvotes: 0

Related Questions