简体   繁体   中英

How to serialize C# objects to generate specific JSON

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

you told it to make the third arg a string. You serialized it to a string then stuck it in as an arg.

you need

parameterList.Add( settle );

First of all, be sure to use newtonsoft.com/json like pm100 mentioned in his comment. I've changed your code so that it would work with newtonsoft.json and got exactly what you've asked for:

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

I removed the DitherParametersList you've created and used those models:

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

And serialized them easily:

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

The quotes are coming from the first serialization that you did here:

string settleStr = settle.SerializeJson();

Assuming that you want to avoid using the Newtonsoft library, an immediate fix would be to simply trim them off:

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

A more robust solution would only require serialization one time. If you used a List{string} instead of a DitherParamtersList , you could do this:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM