1

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

4
  • Validate your JSON using jsonlint.com Commented Jun 9, 2016 at 17:22
  • To generate C# classes based on JSON format, you can use - json2csharp.com Commented Jun 9, 2016 at 17:23
  • 1
    first and foremost - use json.net for json in c#. Thats what MS uses in most places now Commented Jun 9, 2016 at 17:24
  • 1
    Try this: newtonsoft.com/json, ditch DataContractJsonSerializer Commented Jun 9, 2016 at 17:47

3 Answers 3

1

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 );
Sign up to request clarification or add additional context in comments.

7 Comments

He wants it to be a string. Check his question. I suspect a bug in the deserializer he is using.
my reading is that he wants it like the first line in the question
No, I don't think that I want it to be a string. That is probably why the quotes are there.
After 're-rereading' the question, you are probably correct. Let him clarify his question.
Lol then WTH did you do this? string settleStr = settle.SerializeJson(); ?? Just add settle straight away like @pm100 suggested.
|
1

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

3 Comments

So what I need cannot be done with the MS serializer?
as will-ray stated, you can trim the quotes: string settleStr = settle.SerializeJson().Trim('"'); But it's definitely not the right way to go.
Sure, feel free to choose my answer as the solution.
0

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

1 Comment

Thanks, I opted for the Newtonsoft library...Problem solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.