RestSharp JsonDeserializer with special characters in identifiers

北城以北 提交于 2019-12-10 19:29:39

问题


I have some JSON coming from Last.fm like this:

{
   "toptags":{
      "@attr":{
         "artist":"Whatever",
         "album":"Whatever"
      }
   }
}

Is there a special way to setup RestSharp to get it to recognize the @attr? The @ (AT sign) is causing me problems because I can't create an identifier that will match this.


回答1:


From looking at the RestSharp source it's possible to enable it to do data contract deserialization, this seems to require a change of the RestSharp source.

Search for //#define SIMPLE_JSON_DATACONTRACT in SimpleJson.cs

Then you'll need to create the data contracts as well (see "@attr" below):

[DataContract]
public class SomeJson
{
    [DataMember(Name = "toptags")]
    public Tags TopTags { get; set; }
}

[DataContract]
public class Tags
{
    [DataMember(Name = "@attr")]
    public Attr Attr { get; set; }
}

[DataContract]
public class Attr
{
    [DataMember(Name = "artist")]
    public string Artist { get; set; }

    [DataMember(Name = "album")]
    public string Album { get; set; }
}

Didn't try it with RestSharp, but it works with this piece of code, RestSharp uses DataContractJsonSerializer, possibly you will have to set the

SimpleJson.CurrentJsonSerializerStrategy =   
                    SimpleJson.DataContractJsonSerializerStrategy

My test:

var json = "{ \"toptags\":{ \"@attr\":{ \"artist\":\"Whatever\", \"album\":\"Whatever\" }}}";

var serializer = new  DataContractJsonSerializer(typeof(SomeJson));
var result = (SomeJson)serializer.ReadObject(
                               new MemoryStream(Encoding.ASCII.GetBytes(json)));


来源:https://stackoverflow.com/questions/13538529/restsharp-jsondeserializer-with-special-characters-in-identifiers

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