user007
user007

Reputation: 1094

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?

Upvotes: 3

Views: 1170

Answers (1)

Mutation Person
Mutation Person

Reputation: 30530

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;
        }
    }
}

Upvotes: 3

Related Questions