Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize string contains int with comma

Tags:

c#

.net

json.net

I can't deserialize number with comma in json to int. It throw this exception :

Newtonsoft.Json.JsonReaderException : 'Could not convert string to integer: 24,992. Path 'Requests', line 1

This is my code :

public class PriceModel
{
    public DateTime Date { get; set; }
    public int Requests { get; set; }
    public decimal Price { get; set; }
}
string json = "{\"Date\":\"2018-03-23\",\"Requests\":\"24,992\",\"Price\":\"95.96\"}";

PriceModel value = JsonConvert.DeserializeObject<PriceModel>(json, new JsonSerializerSettings
{
    Culture = new CultureInfo("en-US")
});

I want that the "Requests" property have the value 24992.

Is there a solution to resolve this problem ?

Thanks

like image 776
Nathan Bruet Avatar asked Mar 26 '18 15:03

Nathan Bruet


2 Answers

Ok after some research came up with following solution where you don't need to change any type or anything and it works as per your requirement.

While deserializing don't use return type var instead use PriceModel and then other things will remain same.

Create new Class ProcessChildModel which inherits from ProcessModel and overrides Requests property.

    public class PriceModel
    {
        public DateTime Date { get; set; }
        public int Requests { get; set; }
        public decimal Price { get; set; }
    }

    public class PriceModelChild : PriceModel
    {
        public new string Requests
        {
            set
            {
                int num;
                if (int.TryParse(value, NumberStyles.AllowThousands,
                    CultureInfo.InvariantCulture, out num))
                {
                    base.Requests = num;
                }

            }
        }
    }

Then use the new child model to deserialize the data

string json = "{\"Date\":\"2018-03-23\",\"Requests\":\"24,992\",\"Price\":\"95.96\"}";
PriceModel value = JsonConvert.DeserializeObject<PriceModelChild>(json);
like image 154
Rudresha Parameshappa Avatar answered Sep 24 '22 02:09

Rudresha Parameshappa


Redefine your class:

public class PriceModel
{
    public DateTime Date { get; set; }
    public string Requests { get; set; }
    public decimal Price { get; set; }
}

Because the data type int cannot handle the comma. Once the object is deserialized, you can then remove the comma:

int requests;
int.TryParse(value.Requests.Replace(",",""), out requests);
like image 29
vbnet3d Avatar answered Sep 25 '22 02:09

vbnet3d