RestSharp Serialize/Deserialize Naming Conversion

笑着哭i 提交于 2019-12-01 19:49:53

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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!