将列表传递给C#中的JSON文件

时间:2017-11-15 10:41:57

标签: c# json

我想写一个JSON文件并从中读取。

  

我使用Newtonsoft.Json包

我有一个包含对象的列表

private List<LinkElement> links = new List<LinkElement>();

对象结构是

public class LinkElement
{
public LinkElement(string link, string key, string description, string type, string[] tags)
{
       Link = link;
       Description = description;
       Type = type;
       Tags = tags;
}

public string Link { get; set; }

public string Key { get; set; }

public string Description { get; set; }

public string Type { get; set; }

public string[] Tags { get; set; }
}

所以当我从文件中阅读时,我会去

string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<List<LinkElement>>(data);

到文件时,我会去

string newData = JsonConvert.SerializeObject(links);
File.WriteAllText(path, newData);

但似乎列表不是正确的要素。字典是可能的。

有人可以帮我把列表传递给JSON文件吗?

2 个答案:

答案 0 :(得分:1)

这是你可以做的。

首先,您不需要模型中的构造函数。

public class LinkElement
{
    public string Key { get; set; }
    public LinkElementInfo Info { get; set; }
}

public class LinkElementInfo 
{
   public string Link { get; set; }

   public string Description { get; set; }

   public string Type { get; set; }

   public string[] Tags { get; set; }
}

//Example Data
Dictionary<string, LinkElementInfo> links = new Dictionary<string, LinkElementInfo>()
{
  {'a',{...}}
};

答案 1 :(得分:0)

您需要从Key中提取LinkElement并将其用作词典中的键值,如下所示:

public class LinkElement
{
  public string Link { get; set; }
  public string Description { get; set; }
  public string Type { get; set; }
  public string[] Tags { get; set; }
}

private Dictionary<string, LinkElement> links = new Dictionary<string, LinkElement>();

要在links中存储项目,请使用此项:

links.Add(key1, linkElement1);
links.Add(key2, linkElement2);

(或者,如果每个LinkElement需要知道自己的密钥,请将其保留在class并使用此添加:links.Add(linkElement1.Key, linkElement1);等)

要写它,你的代码保持不变 要阅读它,您的代码会稍微改变一下:

string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<Dictionary<string, LinkElement>>(data);