REST api 与 C#.NET 复杂的 json 数据 body 发布

REST api with C#.NET complex json data in body posting

我想在我的应用程序中使用短信网关。这就是为什么我联系了接线员,接线员给了我一个 api 格式。

URL: https://ideabiz.lk/apicall/smsmessaging/v2/outbound/3313/requests

请求header

Content-Type: application/json 
Authorization: Bearer [access token] 
Accept: application/json

Body

{
    "outboundSMSMessageRequest": {
        "address": [
            "tel:+94771234567"
        ],
        "senderAddress": "tel:12345678",
        "outboundSMSTextMessage": {
            "message": "Test Message"
        },
        "clientCorrelator": "123456",
        "receiptRequest": {
            "notifyURL": "http://128.199.174.220:1080/sms/report",
            "callbackData": "some-data-useful-to-the-requester"
        },
        "senderName": "ACME Inc."
    }
}

现在,我已经编写代码了:

RestClient client = new RestClient(@"https://ideabiz.lk/");
RestRequest req = new RestRequest(@"apicall/smsmessaging/v2/outbound/3313/requests", Method.POST);

req.AddHeader("Content-Type", @"application/json");
req.AddHeader("Authorization", @"Bearer " + accessToken.ToString());
req.AddHeader("Accept", @"application/json");

string jSon_Data = @"{'outboundSMSMessageRequest': {'address': ['tel:+94768769027'],'senderAddress': 'tel:3313','outboundSMSTextMessage': {'message': 'Test Message : " + System.DateTime.Now.ToString() + "'},'clientCorrelator': '123456','receiptRequest': {'notifyURL': 'http://128.199.174.220:1080/sms/report','callbackData': 'some-data-useful-to-the-requester'},'senderName': ''}}";


JObject json = JObject.Parse(jSon_Data);
req.AddBody(json);

IRestResponse response = client.Execute(req);
string x = response.Content.ToString();
Console.WriteLine(x.ToString());

当我执行这个程序时,在行

req.AddBody(json);

我的系统崩溃并给出错误信息:

'System.WhosebugException' 类型的未处理异常发生在 System.Windows.Forms.dll

如何使用 C#.NET post 复杂 JSON?

你这里有两个问题:

  1. 需要在调用AddBody前设置RequestFormat = DataFormat.Json:

        req.RequestFormat = DataFormat.Json;
        req.AddBody(json);
    

    在不设置参数的情况下,RestSharp 尝试将 JObject 序列化为 XML 并在某处陷入无限递归 - 最有可能尝试序列化JToken.Parent.

  2. 最新版本的 RestSharp no longer use Json.NET 作为其 JSON 序列化器:

    There is one breaking change: the default Json*Serializer* is no longer 
    compatible with Json.NET. To use Json.NET for serialization, copy the code 
    from https://github.com/restsharp/RestSharp/blob/86b31f9adf049d7fb821de8279154f41a17b36f7/RestSharp/Serializers/JsonSerializer.cs 
    and register it with your client:
    
    var client = new RestClient();
    client.JsonSerializer = new YourCustomSerializer();
    

    RestSharp 的新内置 JSON 序列化程序不理解 JObject 因此,如果您使用的是这些较新版本之一,则需要按照上面的说明进行操作,创建:

    public class JsonDotNetSerializer : ISerializer
    {
        private readonly Newtonsoft.Json.JsonSerializer _serializer;
    
        /// <summary>
        /// Default serializer
        /// </summary>
        public JsonDotNetSerializer() {
            ContentType = "application/json";
            _serializer = new Newtonsoft.Json.JsonSerializer {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Include,
                DefaultValueHandling = DefaultValueHandling.Include
            };
        }
    
        /// <summary>
        /// Default serializer with overload for allowing custom Json.NET settings
        /// </summary>
        public JsonDotNetSerializer(Newtonsoft.Json.JsonSerializer serializer){
            ContentType = "application/json";
            _serializer = serializer;
        }
    
        /// <summary>
        /// Serialize the object as JSON
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>JSON as String</returns>
        public string Serialize(object obj) {
            using (var stringWriter = new StringWriter()) {
                using (var jsonTextWriter = new JsonTextWriter(stringWriter)) {
                    jsonTextWriter.Formatting = Formatting.Indented;
                    jsonTextWriter.QuoteChar = '"';
    
                    _serializer.Serialize(jsonTextWriter, obj);
    
                    var result = stringWriter.ToString();
                    return result;
                }
            }
        }
    
        /// <summary>
        /// Unused for JSON Serialization
        /// </summary>
        public string DateFormat { get; set; }
        /// <summary>
        /// Unused for JSON Serialization
        /// </summary>
        public string RootElement { get; set; }
        /// <summary>
        /// Unused for JSON Serialization
        /// </summary>
        public string Namespace { get; set; }
        /// <summary>
        /// Content type for serialized content
        /// </summary>
        public string ContentType { get; set; }
    }
    

    然后做:

        RestRequest req = new RestRequest(@"apicall/smsmessaging/v2/outbound/3313/requests", Method.POST);
        req.JsonSerializer = new JsonDotNetSerializer();