我的Json文件有以下类:
using System.Collections.Generic;
namespace MITSonWald
{
public class ExtLine
{
public List<Dictionary<string, List<LineList>>> LineList { get; set; }
}
public class LineList
{
public List<Dictionary<string, List<Device>>> DeviceList { get; set; }
}
public class Device
{
public string Volume { get; set; }
public string Name { get; set; }
}
}
生成的Json文件
{
"LineList":[
{
"TapiLine22":[
{
"DeviceList":[
{
"192.168.10.204":[
{
"Volume":"5",
"Name":"Büro"
}
]
}
]
}
]
}
]
}
我想在DeviceList
添加一个对象,但我无法完成。
我尝试了什么
/* Deserialize Json File */
dynamic json =
JsonConvert.DeserializeObject<ExtLine>(
File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "cfg\\lines.json"));
List<Dictionary<string, List<Device>>> myDevice = new List<Dictionary<string, List<Device>>>
{
new Dictionary<string, List<Device>>
{
{
"192.168.10.205",
new List<Device>
{
new Device
{
Name = "Zimmer2",
Volume = "5"
}
}
}
}
};
json.LineList[0]["TapiLine22"][0].DeviceList.Add(myDevice);
抛出异常(Google翻译自德语)
Additional Information: The best match for the overloaded System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <MITSonWald.Device >>>. Add (System.Collections.Generic. Dictionary <string, System.Collections.Generic.List <MITSonWald.Device >>) method contains some invalid arguments.
答案 0 :(得分:1)
从例外情况看,你的Add似乎是:
Add (Dictionary<string, List<MITSonWald.Device>>)
但您要添加
类型的对象List<Dictionary<string, List<Device>>>
这应该有效(但它会取代你的清单):
json.LineList[0]["TapiLine22"][0].DeviceList = myDevice;
因为你的myDevice与DeviceList的类型相同。
您也可以创建字典并将其添加到DeviceList(只需抛出不需要的列表):
var myDevice = new Dictionary<string, List<Device>>
{
{
"192.168.10.205",
new List<Device>
{
new Device
{
Name = "Zimmer2",
Volume = "5"
}
}
}
}