Developer_LA
Developer_LA

Reputation: 75

JSON serializer issue with .Net Core

I have a restful api (.Net Core web api) which calls another api(3rd party) and receives the data in json format. Then this json data is converted in class objects using deserialization.

Issue: JSON data returned from other api contains some decimal values like 325.34723897, However when it is received in restful api, it is only 325 and all decimal values are getting trimmed. 3rd party api is being called using code like below (responseStream itself has trimmed value):

 HttpWebRequest webRequest = GetWebRequest();
        webRequest.Method = "POST";

        UTF8Encoding encoding = new UTF8Encoding();
        Byte[] byteArray = encoding.GetBytes(Request);

        webRequest.ContentLength = byteArray.Length;
        webRequest.Timeout = 60;            

        try
        {
            using (Stream dataStream = webRequest.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            WebResponse webResponse = await webRequest.GetResponseAsync();

            using (Stream responseStream = webResponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                ResponseString = reader.ReadToEnd();
                response = _serializer.DeserializeObject<TResponse>(ResponseString);
            }
        }
        catch (Exception ex)
        {}

How can it be fixed in DotNet Core.

I found some forum where in the solution is given for Dot Net Framework but not for Core (as GlobalConfiguration is not present in Core).

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Culture = new CultureInfo(string.Empty) {
NumberFormat = new NumberFormatInfo {
    CurrencyDecimalDigits = 5
}};

Upvotes: 0

Views: 49

Answers (1)

Serge
Serge

Reputation: 43870

I just tried Newtonsoft.Json to deserialize double property with value 325.34723897 and everything is working properly. You can install it using Nuget. Try this code

 ResponseString = reader.ReadToEnd();
 response = JsonConvert.DeserializeObject<...your class>(ResponseString);

Upvotes: 1

Related Questions