Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON decimal to double

Is there a way to set that JSON would decode variables to double instead of decimal?

example:

[DataContract]
class ReturnData
{
    [DataMember]
    public object[] array { get; set; }
}

public ReturnData DecodeJsonString()
{
    string str = "{ \"array\" : [\"custom array\", 0.1, 0.2, 0.3, 0.4] }";
    var json = new DataContractJsonSerializer(typeof(ReturnData));
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(str));
    var obj = json.ReadObject(stream);
    stream.Close();
    return (ReturnData)obj;
}

I get "obj" array that contains with decimal numbers, but I need it to be double. I don't want to convert to double by my self. Is there a way to teach JsonSerializer to do so?

like image 500
user007 Avatar asked Apr 09 '26 11:04

user007


1 Answers

Are you really constrained to using typeof(object)?

You could create your own custom contract class:

[DataContract]
class MyClass
{
    [DataMember]
    public double[] array { get; set; }
}

And then reference that from the second line:

var json = new DataContractJsonSerializer(typeof(MyClass));

For reference, this was the full console app code that I got working:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;

namespace ConsoleApplication1
{
    [DataContract]
    class MyClass
    {
        [DataMember]
        public double[] array { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            GetStuff();
        }

        static object GetStuff()
        {
            string str = "{ \"array\" : [0.1, 0.2, 0.3, 0.4] }";

            var json = new DataContractJsonSerializer(typeof(MyClass));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(str));
            var obj = json.ReadObject(stream);
            stream.Close();
            return obj;
        }
    }
}
like image 78
James Wiseman Avatar answered Apr 11 '26 23:04

James Wiseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!