简体   繁体   中英

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?

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

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

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