Script in object c #

2

Good I am doing a POST request in C # and I receive the following answer:

 "resp": {
        "clave": "50623081800310267146900100001010000000135127983503",
        "fecha": "2018-08-31T18:05:54-06:00",
        "ind-estado": "aceptado",
        "respuesta-xml": "PD94bWwgdmVyc2lvbj0i    
}

I want to get the code of ind-estado

IRestResponse response2 = client.Execute(request);
 dynamic x= JsonConvert.DeserializeObject<dynamic>(response2.Content);

richTextBox1.Text = " " + x.resp.fecha;

/////////// THAT WORKS ME TO OBTAIN THE DATE. THE PROBLEM IS THAT WHEN I WANT

That works for me to get the date, the problem, is when I want to get x.resp.ind-estado and add it to RichTextBox , Visual Studio marks a syntax error

  

The name estado does not exist in the current context

How can I solve it?

    
asked by arsoft cr 01.09.2018 в 04:09
source

1 answer

3

Your problem is given because C # can not differentiate between a hyphenated name and a subtraction.

Therefore, using Newtonsoft.Json , to solve your problem, first, you must map the format of your Json in a class, and then, you should use the [JsonProperty] annotation to tell C # to correctly map the property.

Let's start, first, we write the class, with its corresponding annotation

public class Resp
{
    public string clave { get; set; }
    public DateTime fecha { get; set; }
    [JsonProperty(PropertyName = "ind-estado")]
    public string indEstado { get; set; }
    [JsonProperty(PropertyName = "respuesta-xml")]
    public string respuestaXML { get; set; }
}

public class RootObject
{
    public Resp resp { get; set; }
}

As you can see, we use the annotation JsonProperty to tell you, that instead of waiting for indEstado , wait ind-estado

Then, just enough, deserialize it as RootObject instead of dynamic

    class Program
    {
        //Defino el response como un string para el ejemplo
        const string response = @"{" +
" \"resp\": {" +
"        \"clave\": \"50623081800310267146900100001010000000135127983503\"," +
"        \"fecha\": \"2018-08-31T18:05:54-06:00\"," +
"        \"ind-estado\": \"aceptado\"," +
"        \"respuesta-xml\": \"PD94bWwgdmVyc2lvbj0i\"   " +
"}" +
"}";


        static void Main(string[] args)
        {
            RootObject a = JsonConvert.DeserializeObject<RootObject>(response);

            Console.WriteLine(a.resp.indEstado);
            Console.WriteLine(a.resp.respuestaXML);
            Console.ReadLine();

        }
    }

I leave you a dotnetfiddle with what I explain to you working

Greetings!

    
answered by 02.09.2018 в 00:55