簡體   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