如何序列化C#对象以生成特定的JSON

时间:2016-06-09 17:18:57

标签: c# json serialization

我正在尝试创建类似于以下内容的JSON,以通过TCP传递给外部。

  

{“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}

注意params数组的第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();


        }
    }
}

提前致谢

3 个答案:

答案 0 :(得分:1)

你告诉它让第三个arg成为一个字符串。你将它序列化为一个字符串,然后将它作为一个arg插入。

你需要

parameterList.Add( settle );

答案 1 :(得分:1)

首先,请务必使用评论中提及的newtonsoft.com/json pm100。 我已经更改了你的代码,以便它可以与newtonsoft.json一起使用并得到你所要求的内容:

{"method": "dither", "params": [10, false, {"pixels": 1.5, "time": 8, "timeout": 40}], "id": 42}

我删除了您创建的DitherParametersList并使用了这些模型:

public class Dither
{
    [JsonProperty("method", Order = 1)]
    public string Method { get; set; }

    [JsonProperty("params", Order = 2)]
    public ArrayList Parameters { get; set; }

    [JsonProperty("id", Order = 3)]
    public int Id { get; set; }
}

public class Settle
{
    [JsonProperty("pixels")]
    public double Pixels { get; set; }

    [JsonProperty("time")]
    public int Time { get; set; }

    [JsonProperty("timeout")]
    public int Timeout { get; set; }
}

并轻松地将它们序列化:

class Program
{
    static void Main(string[] args)
    {
        var settle = new Settle { Pixels = 1.5, Time = 8, Timeout = 40 };
        var parameterList = new ArrayList { 10, false, settle };
        var dither = new Dither { Method = "dither", Parameters = parameterList, Id = 42 };

        string temp = JsonConvert.SerializeObject(dither);
    }
}

答案 2 :(得分:0)

引号来自您在此处执行的第一个序列化:

string settleStr = settle.SerializeJson();

假设您想避免使用Newtonsoft库,立即修复就是简单地修剪它们:

string settleStr = settle.SerializeJson().Trim('"');

更强大的解决方案只需要一次序列化。如果您使用List{string}代替DitherParamtersList,则可以执行此操作:

Settle settle = new Settle { Pixels = 1.5, Time = 8, Timeout = 40 };
var parameterList = new List<string>()
{
    ditherAmount.ToString(),
    ditherRaOnly.ToString(),
    string.Join(",", settle.Pixels, settle.Time, settle.Timeout)
};

Dither dither = new Dither { Method = "dither", Parameters = parameterList, Id = 42 };

string temp = dither.ToJSON();