如何将JSON数组字符串转换为字典?

时间:2015-12-11 17:30:45

标签: c# json json.net

我有一个JSON字符串,如下所示:

[{"Id":"1","Name":"Apple "},{"Id":"2","Name":"Orange "},{"Id":"3","Name":"Banana "}....]

如何将JSON字符串转换为这种格式:{"1":"Apple"},{"2":"Orange"},{"3","Banana"}...所以我可以创建如下字典:

Dictionary<string, string> d = new Dictionary<string, string>()
    {
        {"1":"Apple"},{"2":"Orange"},{"3","Banana"}
    };

1 个答案:

答案 0 :(得分:1)

您不需要将原始字符串实际转换为其他格式。

使用中间类,如下所示,您可以直接转换:

using Newtonsoft.Json;
using System.Linq;

Dictionary<string, string> tt = JsonConvert.DeserializeObject<List<DataObject>>(@"[{""Id"":""1"",""Name"":""Apple ""},{""Id"":""2"",""Name"":""Orange ""},{""Id"":""3"",""Name"":""Banana ""}]").ToDictionary(k => k.Id, v => v.Name);

public class DataObject
{
    public string Id { get; set; }
    public string Name { get; set; }
}

所以这样做首先将Json数组转换为List<DataObject>,然后使用Linq ToDictionary运算符完成工作。

希望这有帮助