Search code examples
c#jsonasp.net-coreserializationjson.net

How to convert JSON values that START with a NUMBER to C# Class


I use a web service whose output fields starts with a number like the below

[{"1_sell_count":"1","2_sell_count":"2","3_sell_count":"2"}]

Since I can't have a variable in C # that starts with a number and If I change the property name, the JsonConvert.DeserializeObject method cannot do the conversion JSON To my Class.

how can I convert this JSON output to a C# class?

    List<myclass> reservationList = new List<myclass>();
    using (var response = await httpClient.GetAsync(urlApi))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();
                        reservationList = JsonConvert.DeserializeObject<List<myclass>>(apiResponse);
                    }

and myclass.cs

 public class myclass
    {
        public string 1_sell_count{ get; set; }  //Not Valid Name
        public string 2_sell_count{ get; set; }   //Not Valid Name
        public string 3_sell_count{ get; set; }    //Not Valid Name
    }

What is the solution to this problem?


Solution

  • You can attach the JsonProperty attribute over property as shown below which instructs the JsonSerializer to always serialize the member with the specified name

    public class myclass
    {
        [JsonProperty("1_sell_count")]
    
        public string First_sell_count{ get; set; }  
        [JsonProperty("2_sell_count")]
        public string Second_sell_count{ get; set; }   
        
        [JsonProperty("3_sell_count")]
        public string Third_sell_count{ get; set; }    
    }
    

    See the fiddle - https://dotnetfiddle.net/xGhtxv

    With above your conversion logic would remain intact i.e.

    reservationList = JsonConvert.DeserializeObject<List<myclass>>(apiResponse);
    

    However, you should be using the property name defined in the class to access the property in C# code.