繁体   English   中英

正文中具有C#.NET复杂json数据的REST api

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

我想在我的应用程序中使用短信网关。 这就是为什么我与运营商联系,而运营商给我提供了一种api格式的原因。

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

请求标头

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

身体

{
    "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.Windows.Forms.dll中发生了类型为'System.StackOverflowException'的未处理异常

如何使用C#.NET发布复杂的JSON?

您在这里有两个问题:

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

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

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

  2. RestSharp的更新版本不再使用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(); 

暂无
暂无

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

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