1

使用此代码:

var button = Value.ForStruct(new Struct{
    Fields={
        ["type"] = Value.ForString("postback"),
        ["title"] = Value.ForString("Call Representative"),
        ["payload"] =  Value.ForString("+15105551234"),
    }
});

var inPayload = Value.ForStruct(new Struct{
    Fields ={
        ["buttons"] = Value.ForList(button),
        ["text"] = Value.ForString("try the postback"),
        ["template_type"] = Value.ForString("button"),
    }
});

var attachment = Value.ForStruct(new Struct{
    Fields ={
        ["payload"] = inPayload,
        ["type"] = Value.ForString("template"),
    }
});

var msg = Value.ForStruct(new Struct{
    Fields ={
        ["attachment"] = attachment,
    });

Payload = new Struct{
    Fields ={
        ["facebook"] = msg
    }

我能够创建以下json:

"payload":    {
      "facebook": {"attachment":       {
         "payload":          {
            "buttons": [            {
               "type": "postback",
               "title": "Call Representative",
               "payload": "+15105551234"
            }],
            "text": "try the postback",
            "template_type": "button"
         },
         "type": "template"
      }}

现在我需要创建以下其他格式,但我不知道该怎么做:

"payload":    {
         "message": "Yes I did it"
         "platform": "kommunicate",
         "attachment":       {
             "payload":          {
                "buttons": [            {
                   "type": "postback",
                   "title": "Call Representative",
                   "payload": "+15105551234"
                }],
                "text": "try the postback",
                "template_type": "button"
             },
             "type": "template"
          }

我真的不知道如何消除第一个“facebook”:{元素并只留下:

  {
    "message": "Yes I did it",
    "platform": "kommunicate",
    "attachment":

并包括消息和平台在同一级别。这是我要生成的完整 json:

"payload":    {
   "platform": "kommunicate",
   "message": "Yes I did it",
   "attachment":       {
         "payload":          {
            "buttons": [            {
               "type": "postback",
               "title": "Call Representative",
               "payload": "+15105551234"
            }],
            "text": "try the postbackggggggg",
            "template_type": "button"
         },
         "type": "template"
      }
4

1 回答 1

2

如果您想获取一个对象并将其转换为 json,我建议您查看Newtonsoft Json.Net library。他们有很多例子可以帮助你。还有用于序列化为 protobuf 而不是 json 的protobuf.net库。

这两个库的使用方式相似,您创建一个具有适当属性的类并设置所需的值。如您的示例所示,您将需要多个嵌套类型的类。Protobuf 要求您使用属性注释属性,而这对于 json.net 是可选的。然后将对象发送到序列化库并获取代表对象的字符串或二进制数据。这种对象通常称为数据传输对象 (DTO),因为它的唯一目的是帮助序列化或/和将数据传输到另一个系统。

于 2020-02-21T15:03:23.740 回答