如何在C#中反序列化具有动态属性名称的对象?

时间:2019-05-13 16:19:50

标签: c# .net c#-4.0

在对象GistObject中反序列化API响应之后,包含在类GistObject中的对象之一为null我注意到对象名称的属性根据API的链接而变化,我的问题是我反序列化具有动态名称的该对象? API响应的json粘贴在此处:https://gist.github.com/PontiacGTX/dd126c9379c608e4520a9d6744f0d234第11行根据要旨网址更改其名称

代码的编写方式: https://gist.github.com/PontiacGTX/d99835d35fb2f29e4382bd23656b860f

private static void GetGistUrl(ref string localurl, ref string fileName, ref string extension)
{
    fileName = "";
    string gistAPI = gistAPIUrl;
    int gistIndexBegin = GetIndex(url, '/', 4);
    int gistIndexEnd = url.IndexOf('#', 1) > 0 ? url.IndexOf('#', 1) : url.Length;
    string gistID = url.Substring(gistIndexBegin + 1, gistIndexEnd - (gistIndexBegin + 1));

    gistAPI = gistAPIUrl.Replace(":gist_id", gistID);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gistAPI);
    request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36";
    request.Method = WebRequestMethods.Http.Get;
    request.Timeout = 5000;
    Stream response = request.GetResponse().GetResponseStream();
    StreamReader readstream = new StreamReader(response);
    string responsetr = readstream.ReadToEnd();
    readstream.Dispose();
    readstream.Close();
    var gistResultObj = JsonConvert.DeserializeObject<IList<GistObject>>(responsetr).ToList();


    for (int i = 0; i < gistResultObj.Count; 
    {
        foreach (FileObject obj in gistResultObj[i]._files)
        {
            if (!string.IsNullOrEmpty(obj._file.raw_url))
            {
                localurl = obj._file.raw_url;
            }

            if (!string.IsNullOrEmpty(obj._file._filename))
            {
                fileName = obj._file._filename;
            }
        }
    }

    if (fileName == "")
    {
        fileName = gistID;
    }

    extension = Path.GetExtension(localurl);
}

0 个答案:

没有答案