PrimuS PrimuS - 25 days ago 10
C# Question

Create JSON with value as object

Not sure if the title matches what I actually want, suggestions welcome.

I create a JSON file like this:

{
"Sonos": [
{
"Ips": [
{
"Volume": "5",
"ip": "192.168.10.214"
},
{
"Volume": "5",
"ip": "192.168.10.204"
}
]
}
]
}


Class

public class GetConfig
{
public List<Cfg> Sonos { get; set; }
}

public class Cfg
{
public List<Ip> Ips { get; set; }
}

public class Ip
{
public string Volume { get; set; }
public string ip { get; set; }
}


Create JSON

var list = new List<Cfg>();
var ips = new List<Ip>();

foreach (ListViewItem item in sonosListExt1.Items)
{

ips.Add(new Ip {Volume = "5", ip = item.Text });
}

list.Add(new Cfg { Ips = ips });

var gC = new GetConfig
{
Sonos = list
};
...
//WRITE TO FILE


What I actually want (not sure if valid though)

{
"Sonos": [
{
"192.168.10.214": [
{
"Volume": "5"
},
"192.168.10.204": [
{
"Volume": "5"
}
]
}
]}


I don't know how I can create the actual IP as an object that contains the Volume of the said IP.
Or maybe I need a different approach?

What I want to do

I have a list with IPs, loop through this list and want to get the Volume from the
config.json
file, is there maybe a better way?

Answer

You JSON is invalid, I assume your JSON is:

{
  "Sonos": [
    {
      "192.168.10.214": [
        {
          "Volume": "5"
        }
      ],
      "192.168.10.204": [
        {
          "Volume": "5"
        }
      ]
    }
  ]
}

If so, you could deserialize it via this class structure:

class Container
{
    public List<Dictionary<string, List<Cfg>>> Sonos { get; set;}
}

class Cfg
{
    public string Volume { get; set; }
}

// ...
var container = JsonConvert.DeserializeObject<Container>(json);

Creating a model for the JSON could be achieved via:

var container = new Container();
container.Sonos = new List<Dictionary<string, List<Cfg>>>
{
    new Dictionary<string, List<Cfg>>
    {
        { "192.168.10.214", new List<Cfg> { new Cfg { Volume = "5" } } }
    }
};

var json = JsonConvert.SerializeObject(container);
Comments