0

我正在尝试从 .json 文件中解析数据,并将它们放在一个名为“Track”的类的列表中

该类如下所示:

public class Track
{
        public string Artist { get; set; }
        public string Album { get; set; }
        public string Title { get; set; }
        public int TrackNumber { get; set; }
        public string Filepath { get; set; }
        public int SongLength { get; set; }
        public Color RGB { get; set; }
}

我的代码如下所示:

private void Load()
    {
        using (StreamReader r = new StreamReader("C:\Users\Swagger\Desktop\Test\MusicCacheP.json"))
        {
            string json = r.ReadToEnd();
            List<Track> items = JsonConvert.DeserializeObject<List<Track>>(json);
            MSG(items.Count.ToString());
            //MSG is just a function which gives me a messagebox. I'm too lazy to write the full messagebox.show.. ;)
        }

    }

而且我不知道这是否重要,但这里有一些 json 代码:

{"Artist":"Dirty South","Album":"Until the End","Title":"Until the End (Michael Brun Mix) [feat. Joe Gil]","TrackNumber":0,"Filepath":"\\\\DAVIDIOSO\\Users\\hasht_000\\Music\\Dirty South - Until the End (Michael Brun Mix) [feat. Joe Gil].mp3","SongLength":21,"RGB":""}

我还没有真正使用过 Json 来完全了解它是如何工作的。我是那种喜欢边做边学的人。但是,如果您有一些关于 C# 中 json 的好书要阅读,我会很高兴阅读它 :)

编辑:

我要疯了!我不知道为什么我会得到这个例外..

我只收到文件路径的例外情况。

疯狂的是我有另一个文件,里面有所有的文件路径,我也用 json 读取。效果很好。

“贫民窟”解决方案是读取仅包含文件路径的文件并使用它来填充我的 Track 列表?但如果能解决这个问题会很好。任何帮助都非常感谢!:)

4

2 回答 2

2

So, I feel quite embarrassed to have to answer this myself.

What I forgot to do, was to remove a letter "p" from the filereader. So it got the file with only filepaths for the music instead of artists, track names, album names etc etc...

I can't believe I didn't see it until now!

It's been like 2-3 days since I first got this problem and it was SUCH an easy fix..

于 2013-10-09T21:05:48.673 回答
2

您已经在您的班级中定义RGB了 as以及您在指向字符串类型时所拥有的内容。您可以将您的类修改为具有字符串类型,然后将该字符串值转换为.ColorjsonRGBColor

public class RootObject
{
    public string Artist { get; set; }
    public string Album { get; set; }
    public string Title { get; set; }
    public int TrackNumber { get; set; }
    public string Filepath { get; set; }
    public int SongLength { get; set; }
    public string RGB { get; set; } //here
}

要从 json 自动创建类模板,请使用http://json2csharp.com/

于 2013-10-08T21:07:54.490 回答