JSON decimal double
Is there a way to set that JSON will 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 an array "obj" which contains decimal numbers, but I need it to be double. I don't want to turn into a double self. Is there a way to teach the JsonSerializer to do this?
+3
source to share
1 answer
Are you really limited in use typeof(object)
?
You can create your own contract class:
[DataContract]
class MyClass
{
[DataMember]
public double[] array { get; set; }
}
And then specify that from the second line:
var json = new DataContractJsonSerializer(typeof(MyClass));
For reference, this was the complete console application code I received:
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;
}
}
}
+3
source to share