PrimuS PrimuS - 17 days ago 8
C# Question

Update json Object w/ json.net

I have the following class for my Json file:

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; }
}
}


Resulting Json File

{
"LineList":[
{
"TapiLine22":[
{
"DeviceList":[
{
"192.168.10.204":[
{
"Volume":"5",
"Name":"Büro"
}
]
}
]
}
]
}
]
}


I would like to add an object to the
DeviceList
but I can't get it done.

What I tried

/* 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);


Thrown Exception (Google Translate from German)

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.

Answer

From the exception it looks like your Add is expecting:

Add (Dictionary<string, List<MITSonWald.Device>>)

This should work:

json.LineList[0]["TapiLine22"][0].DeviceList = myDevice;

because myDevice is the same type as DeviceList.

You could also create dictionary and add it to DeviceList:

var myDevice = new Dictionary<string, List<Device>>
{
    {
        "192.168.10.205",
        new List<Device>
        {
            new Device
            {
                Name = "Zimmer2",
                Volume = "5"
            }
        }
    }
}
Comments