我正在嘗試創建類似以下的JSON以通過TCP傳遞給外部。如何序列化C#對象以生成特定的JSON
{"method": "dither", "params": [10, false, {"pixels": 1.5, "time": 8, "timeout": 40}], "id": 42}
我差點,但是這是我而不是:
{"method": "dither", "params": [10, false,"{"pixels": 1.5, "time": 8, "timeout": 40}"], "id": 42}
注意周圍的參數數組的第3元素引號。
我希望在解決這個問題上有任何幫助。這裏是我的代碼:
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();
}
}
}
在此先感謝
使用http://jsonlint.com/ – Sanket
要基於JSON格式的C#類驗證您的JSON,你可以使用 - HTTP ://json2csharp.com/ – Sanket
首先 - 在c#中使用json.net for json。多數民衆贊成現在在大多數地方使用 – pm100