本文介绍了RestSharp JsonDeserializer与标识符特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JSON从Last.fm未来是这样的:

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

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

有没有设置RestSharp一种特殊的方式来得到它承认在 @attr ?在@(at符号)是引起了我的问题,因为我无法创建一个标识符,将符合这一点。

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.

推荐答案

从看在RestSharp源有可能使它能够做数据契约反序列化,这似乎需要RestSharp源的变化。

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.

搜索 / /#定义SIMPLE_JSON_DATACONTRACT 在SimpleJson.cs

Search for //#define SIMPLE_JSON_DATACONTRACT in SimpleJson.cs

然后你需要创建一个数据契约以及(见@ ATTR 以下):

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; }
}

没有在RestSharp尝试,但它这片作品代码,RestSharp使用DataContractJsonSerializer,可能你将不得不设置

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

我的测试:

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

这篇关于RestSharp JsonDeserializer与标识符特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 04:14