Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp JsonDeserializer with special characters in identifiers

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.

like image 236
programmer Avatar asked Jan 17 '26 20:01

programmer


1 Answers

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)));
like image 88
Tommy Grovnes Avatar answered Jan 19 '26 18:01

Tommy Grovnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!