【问题标题】:REST api with C#.NET complex json data in body posting正文发布中带有 C#.NET 复杂 json 数据的 REST api
【发布时间】:2015-12-05 18:54:59
【问题描述】:

我想在我的应用程序中使用短信网关。所以我联系了运营商,运营商给了我一个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?

【问题讨论】:

    标签: c# json rest restsharp


    【解决方案1】:

    这里有两个问题:

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

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

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

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

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

    【讨论】:

    • 按照此说明操作后,一切正常。谢谢@dbc。
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2020-11-06
    • 2016-09-12
    • 2013-09-30
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多