繁体   English   中英

C#JSON反序列化iTunes搜索API

[英]C# json deserialization itunes search api

我只是无法使这种反序列化工作。 它没有错误,但artistName保持为空。

有人可以帮忙吗?

Json字符串:

{“ resultCount”:1,“ results”:[{“ wrapperType”:“ track”,“ kind”:“ song”,“ artistId”:414401,“ collectionId”:6666512,“ trackId”:6666508,“ artistName” :“关闭自动驾驶仪”,“ collectionName”:“发出声音”,“ trackName”:“ Byron Black”,“ collectionCensoredName”:“发出声音”,[...]“

HttpWebRequest webRequest;

    void StartWebRequest(string itunesUrl)
    {
        webRequest = (HttpWebRequest)WebRequest.Create(itunesUrl); 
        webRequest.Method = "GET";
        webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);

    }

    void FinishWebRequest(IAsyncResult result)
    {

        StreamReader sr = new StreamReader(webRequest.EndGetResponse(result).GetResponseStream());
        string json = sr.ReadToEnd();

        Log.debugToVS("json: " + json);


        iTunesResult itunesObj = new iTunesResult();

        itunesObj = JSONHelper.Deserialise<iTunesResult>(json);

        Log.debugToVS("artistId: " + itunesObj.artistName);

    }

    public void iTunesSearch(string artist, string album, string title)
    {

        if(artist == "" && album == "" && title == "") return;

        string query = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?";

        query += "term=" + HttpUtility.UrlEncode(artist + " " + album + " " + title);

        query += "&media=music";
        query += "&limit=20";

        Log.debugToVS("url: " + query);

        StartWebRequest(query); 
    }

}

public class JSONHelper
{
    public static T Deserialise<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();

        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms); // <== Your missing line



            return obj;

    }
}

[DataContract]
public class iTunesResult
{
    [DataMember]
    public string artistName { get; set; }
}

我认为您的数据合同有问题。 查看Json的数据合约应该是这样的。

[DataContract]
public class iTunesResult
{
    [DataMember]
    public iTuneJsonResults[] results { get; set; }
}


[DataContract]
public class iTuneJsonResults
{
    [DataMember]
    public string artistName { get; set; }
}

并且FinishWebrequest中Log.xxxx的行应变为:

foreach(var item in itunesObj.results)
     Log.debugToVS("artistId: " + item.artistName);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM