RestSharp Serialize/Deserialize Naming Conversion

前端 未结 1 1344
甜味超标
甜味超标 2021-01-20 00:04

I am attempting to wrap the Plivo API (yes I\'m aware it\'s been done) using RestSharp.

However, I cannot find a method to translate the API Naming conventi

1条回答
  •  臣服心动
    2021-01-20 00:40

    Unfortunately it looks as though JSON property renaming is not implemented out of the box in RestSharp. You have a couple of options:

    1. Download Restsharp from https://github.com/restsharp/RestSharp and rebuild it yourself enabling the compiler option SIMPLE_JSON_DATACONTRACT. Then you will be able to rename properties using data contract attributes. For more, see here: RestSharp JsonDeserializer with special characters in identifiers

      I just rebuilt the most recent version of RestSharp (version 105.1.0) with this option enabled. Using the following version of your class:

      [DataContract]
      public class CallRequest
      {
          [DataMember(Name = "from")]
          public string From { get; set; }
      
          [DataMember(Name = "to")]
          public string To { get; set; }
      
          [DataMember(Name = "answer_url")]
          public string AnswerUrl { get; set; }
      }
      

      I was able to generate the following JSON:

          var request = new CallRequest { AnswerUrl = "AnswerUrl", From = "from", To = "to" };
          var json = SimpleJson.SerializeObject(request);
          Debug.WriteLine(json);
          // Prints {"from":"from","to":"to","answer_url":"AnswerUrl"}
      

      I'm not sure how thoroughly tested this option is, however, since it's compiled out by default.

    2. Manually serialize and deserialize with a different serializer such as Json.NET that supports property renaming. To do this, see RestSharp - using the Json.net serializer (archived here.)

    0 讨论(0)
提交回复
热议问题