Convert JSON containing backslash using C #

1

I tell you that I am consuming a REST service from a third party, when I make the call this returns me a json, the problem is that the json comes in the following way: (Here is a fragment of the JSON)

"GetBookingResult": "{\"reserva\":{\"fecha_creacion\":{\"#text\":\"15FEB17\"},\"hora_creacion\":{\"#text\":\"2133\"},\"responsable\":{\"tipo_reserva\":\"WEBPAS\",\"cod_cia\":\"OB\",\"off_resp\":\"OBW101\"},\"localizador_resiber\":{\"#text\":\"P7S44\"}

This is the code I am using to consume the service

public static Reserva getBooking(GetBookingRequest requestParams)
        {
            try
            {
                StreamWriter requestWriter;

                string postData = new JavaScriptSerializer().Serialize(requestParams);

                var webRequest = System.Net.WebRequest.Create("http://miUrl.svc/metodo") as HttpWebRequest;
                if (webRequest != null)
                {
                    webRequest.Method = "POST";
                    webRequest.ServicePoint.Expect100Continue = false;
                    webRequest.Timeout = 20000;
                    webRequest.ContentType = "application/json; charset=utf-8";
                    //POST the data.
                    using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                    {
                        requestWriter.Write(postData);
                    }
                }

                using (HttpWebResponse resp = webRequest.GetResponse() as HttpWebResponse)
                {
                    if (resp.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                        resp.StatusCode,
                        resp.StatusDescription));

                    Stream resStream = resp.GetResponseStream();
                    StreamReader reader = new StreamReader(resStream);
                    var resultado = reader.ReadToEnd();
                    Console.WriteLine(resultado);

                    var str = resultado.Replace(@"\", string.Empty);

                    JToken token = JToken.Parse(str);
                    JObject o = JObject.Parse((string)token);


                    JObject response = o["reserva"] as JObject;
                    GetBookingResponse respuesta = response.ToObject<GetBookingResponse>();

                    return respuesta.reserva;
                }              
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ocurrio un error obteniendo los datos de la reserva");
                return null;
            }
        }

in the end what I'm trying to do is get the reserve element of the json that returns the service and convert it to a reservation type object that I created in .NET

    
asked by Christian Gonzalez 23.02.2017 в 00:25
source

3 answers

1

As you are told, it is not the problem of the parse code, but rather the string that is a supposed JSON. It is invalid , at least the one that you set as an example.

First of all, in C # in chains the character \ is an escape character, more info here

This json that you provide if we remove the escape characters \ "replacing \" and testing online in a json parser

"GetBookingResult": "{\"reserva\":{\"fecha_creacion\":{\"#text\":\"15FEB17\"},\"hora_creacion\":{\"#text\":\"2133\"},\"responsable\":{\"tipo_reserva\":\"WEBPAS\",\"cod_cia\":\"OB\",\"off_resp\":\"OBW101\"},\"localizador_resiber\":{\"#text\":\"P7S44\"}

You're badly armed, you can try

If you see something like this  - It does not start with a {} or [] character object or array of objects in json

From the beginning we can say that the assembly is badly armed, it should start as an array or an object {}, It would be something simple, to have a look at it

{"GetBookingResult":1}

If it is complete as it should be (without the escape character to try online)

 {"GetBookingResult": {"reserva":{"fecha_creacion":{"#text":"15FEB17"}, "hora_creacion":{"#text":"2133"}, "responsable":{"tipo_reserva":"WEBPAS","cod_cia":"OB","off_resp":"OBW101"},"localizador_resiber":{"#text":"P7S44"}}}}

But that's why I do not know if what you send is a complete GetBookingResult, or it's a Request GetBookingResult variable that inside has a string that is a json, since it's after GetBookingResult: if it looks like an object JSON (although it is necessary to close some keys at the end)

But assuming you can tell the sender to send it correctly with everything that we are proposing, here is the code to pause in a dymamic and read each part of the json object

 var jsonData =         "{\"GetBookingResult\": {\"reserva\":{\"fecha_creacion\":{\"#text\":\"15FEB17\"}, \"hora_creacion\":{\"#text\":\"2133\"}, \"responsable\":{\"tipo_reserva\":\"WEBPAS\",\"cod_cia\":\"OB\",\"off_resp\":\"OBW101\"},\"localizador_resiber\":{\"#text\":\"P7S44\"}}}}";

        dynamic demo = Newtonsoft.Json.Linq.JObject.Parse(jsonData);

        Console.WriteLine(demo.GetBookingResult);
        Console.WriteLine(demo.GetBookingResult.reserva);
        Console.WriteLine(demo.GetBookingResult.reserva.fecha_creacion);
        Console.WriteLine(demo.GetBookingResult.reserva.hora_creacion);
        Console.WriteLine(demo.GetBookingResult.reserva.responsable);

       Console.WriteLine(demo.GetBookingResult.reserva.localizador_resiber);
    
answered by 30.05.2018 в 15:44
0

In what specific line is it that you get the error? I guess you do not get to convert to JObject .
In these cases you do not need to do Replace , what I normally do is the following:

JObject obj = JObject.Parse(resultado);

Where resultado has the string returned by the service including the \ . And then you convert your entity the way you prefer.

    
answered by 28.02.2017 в 22:31
0

I've been watching your Json and the first thing to tell you is quite rarely formed. To give you an idea that json to pass a validation pause should be like this:

{"GetBookingResult": {"reserva":{"fecha_creacion":{"#text":"15FEB17"},"hora_creacion":{"#text":"2133"},"responsable":{"tipo_reserva":"WEBPAS","cod_cia":"OB","off_resp":"OBW101"},"localizador_resiber":{"#text":"P7S44"}}}}

You have more than enough that you already have it resolved, but you also need a {at the beginning of everything, you have three) at the end of everything and you have some left over "just before {" reserve "}.

Changing that and you should be able to parse it to class without problem with Newtonsoft or with the own .Net and from there to get the data.

Adapting it to c # I get this class structure

    public class Rootobject
    {
        public Getbookingresult GetBookingResult { get; set; }
    }

    public class Getbookingresult
    {
        public Reserva reserva { get; set; }
    }

    public class Reserva
    {
        public Fecha_Creacion fecha_creacion { get; set; }
        public Hora_Creacion hora_creacion { get; set; }
        public Responsable responsable { get; set; }
        public Localizador_Resiber localizador_resiber { get; set; }
    }

    public class Fecha_Creacion
    {
        public string text { get; set; }
    }

    public class Hora_Creacion
    {
        public string text { get; set; }
    }

    public class Responsable
    {
        public string tipo_reserva { get; set; }
        public string cod_cia { get; set; }
        public string off_resp { get; set; }
    }

    public class Localizador_Resiber
    {
        public string text { get; set; }
    }

Does that Json form you or does it come from somewhere already done?

    
answered by 15.02.2018 в 09:52