RestSharp JsonDeserializer with special characters

2019-07-04 21:25发布

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条回答
做自己的国王
2楼-- · 2019-07-04 22:13

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)));
查看更多
登录 后发表回答