How to deserialize a JSON in C # with the following structure?

-3

A web service returns this JSON, which I set in a variable:

 [{
   "PO": "",
   "Status": "S",
   "Message": "OK WO : 000144439642 has been held in KIT1",
   "Process": "HOLD (OTM_TRIGGER)",
   "Auxiliary": "000144439642",
   "TicketNumber": "251765"
 }]

I have already tried many ways but I can not deserialize it. I need to get the values to insert into a DB.

this is what I've been testing:

public class Work_Order
    {
        public string Wo { get; set; }
        public string Status { get; set; }
        public string Message { get; set; }
        public string Process { get; set; }
        public string Auxiliary { get; set; }
        public string Ticket { get; set; }
    }

class Program
    {
        static void Main(string[] args)
        {
        string json = "[{\"PO\":\"\",\"Status\":\"S\",\"Message\":\"OK WO : 000144439642 has been held in KIT1\",\"Process\":\"HOLD (OTM_TRIGGER)\",\"Auxiliary\":\"000144439642\",\"TicketNumber\":\"251765\"}]";


            Work_Order wo = JsonConvert.DeserializeObject<Work_Order>(json);            

            /*este writeline es una prueba para validar que los datos esten seteados*/
            Console.WriteLine(Convert.ToString(wo.Wo) + " " + Convert.ToString(wo.Status) + " " + Convert.ToString(wo.Message) + " " + Convert.ToString(wo.Process) + " " + Convert.ToString(wo.Auxiliary) + " " + Convert.ToString(wo.Ticket));


            Console.WriteLine();
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }

Thanks in advance Greetings!

    
asked by Eli Atseuc 15.11.2018 в 19:14
source

1 answer

4

There are 2 problems in the code,

  • You are trying to deserialize a JSON array within a single variable, change it to a list:

     var items = JsonConvert.DeserializeObject<List<Work_Order>>(json);
    
  • Some names of the properties do not match those of your class, change them or use the JsonProperty attribute to make them fit:

    public class Work_Order
    {
        [JsonProperty("PO")]
        public string Wo { get; set; }
    
        // ...
    
        [JsonProperty("TicketNumber")]
        public string Ticket { get; set; }
    }
    
  • answered by 15.11.2018 / 19:33
    source