I am trying to create JSON like the following to pass to an external via TCP.
{"method": "dither", "params": [10, false, {"pixels": 1.5, "time": 8, "timeout": 40}], "id": 42}
I came close, but this is what I got instead:
{"method": "dither", "params": [10, false,"{"pixels": 1.5, "time": 8, "timeout": 40}"], "id": 42}
Notice the quote marks around the 3rd element of the params array.
I would appreciate any help in resolving this. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Collections;
using System.Xml;
using System.Reflection;
namespace DitherTest
{
[CollectionDataContract]
public class DitherParametersList : ArrayList
{
public DitherParametersList() : base()
{}
}
[DataContract]
public class Dither
{
[DataMember( Name="method", Order=1)]
public string Method { get; set; }
[DataMember( Name="params", Order=2)]
public DitherParametersList Parameters { get; set; }
[DataMember( Name="id", Order=3)]
public int Id { get; set; }
}
[DataContract( Namespace="")]
public class Settle
{
[DataMember( Name = "pixels" )]
public double Pixels { get; set; }
[DataMember( Name = "time" )]
public int Time { get; set; }
[DataMember( Name = "timeout" )]
public int Timeout { get; set; }
public string SerializeJson()
{
return this.ToJSON();
}
}
static class Extensions
{
public static string ToJSON<T>( this T obj ) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof( T ) );
using ( MemoryStream stream = new MemoryStream() )
{
serializer.WriteObject( stream, obj );
return Encoding.Default.GetString( stream.ToArray() );
}
}
}
class Program
{
static void Main( string[] args )
{
double ditherAmount = 10.0;
bool ditherRaOnly = false;
Settle settle = new Settle { Pixels = 1.5, Time = 8, Timeout = 40 };
DitherParametersList parameterList = new DitherParametersList();
parameterList.Add( ditherAmount );
parameterList.Add( ditherRaOnly );
string settleStr = settle.SerializeJson();
parameterList.Add( settleStr );
Dither dither = new Dither { Method = "dither", Parameters = parameterList, Id=42 };
string temp = dither.ToJSON();
}
}
}
Thanks in advance
DataContractJsonSerializer