繁体   English   中英

Newtonsoft.Json C# :: 格式化 JsonConvert.SerializeObject

[英]Newtonsoft.Json C# :: Formatting JsonConvert.SerializeObject

我有以下课程,

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

我正在使用以下内容生成 Json

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

这让我跟随 Json,

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

这很好,但我将其发送到 Twilio API,它具有以下格式的要求,

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

所以我的问题是,我需要在我的类/NewtonSoft 中进行哪些更改才能在单独的花括号中获取每个属性 [say&listen]?

由于您的类已经被称为Actions ,您可以执行以下操作:

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

用法:

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

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

用法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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