Max
Max

Reputation: 1548

Newtonsoft.Json C# :: Formatting JsonConvert.SerializeObject

I have following classes,

  public class Actions
        {
            public string say { get; set; }
            public bool? listen { get; set; }
        }

        public class ActionsWrapper 
        { 
            public List<Actions> actions { get; set; }
            public ActionsWrapper(string say, bool listen = false)
            {
                this.actions = new List<Actions>();

                var action = new Actions();
                action.say = say;
                action.listen = listen;
                this.actions.Add(action);
            }
        }

And I am using the following to generate Json

var actions = new ActionsWrapper(say: "Hi, how can I help you today?");
return JsonConvert.SerializeObject(actions);

This returns me following Json,

{"actions":[
      {
        "say":"Hi, how can I help you today?",
         "listen": false
       }
]}

Which is good, but I am sending this to Twilio API which has the requirement of the following format,

{
  "actions": [
    {
      "say": "Hi, how can I help you today?"
    },
    {
      "listen": false
    }
  ]
}

So my question is, what changes do I need in my classes / NewtonSoft to get each property [say&listen] in separate curly braces?

Upvotes: 0

Views: 494

Answers (2)

weichch
weichch

Reputation: 10035

Since your class is already called Actions, you could do something like this:

[Serializable]
public class Actions : ISerializable
{
    public string say { get; set; }
    public bool? listen { get; set; }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("actions", new object[] { new { say }, new { listen } });
    }
}

Usage:

var actions = new Actions();
actions.say = say;
actions.listen = listen;
var json = JsonConvert.SerializeObject(actions);

Upvotes: 1

Sina Hoseinkhani
Sina Hoseinkhani

Reputation: 328

A solution using Newtonsoft.Json:

public class Say
{
    public string say { get; set; }
}

public class Listen
{
    public bool? listen { get; set; }
}

public class ActionsWrapper
{
    public List<Say> Says { get; set; }
    public List<Listen> Listens { get; set; }
    public ActionsWrapper(string say, bool listen = false)
    {
        this.Says = new List<Say>();
        this.Listens = new List<Listen>();
        Says.Add(new Say() { say = say });
        Listens.Add(new Listen() { listen = listen });
    }
}

Usage:

var actions = new ActionsWrapper(say: "Hi, how can I help you today?");

JArray JArraySays = JArray.FromObject(actions.Says);
JArray JArrayListens = JArray.FromObject(actions.Listens);
JArraySays.Merge(JArrayListens);

return JsonConvert.SerializeObject(new { actions = JArraySays });

Upvotes: 1

Related Questions