I have been asked to supply data in a json in the following format:
{
"testsystem": "1.0.0",
"playback": {
"1": {
"cue": 1,
"state": "Stopped",
"label": "Hello"
},
"2": {
"cue": 100,
"state": "Running",
"label": "Hello"
}
}
}
I have been using Newtonsoft json to serialise the information but there a couple of points which confuse me.
public class Company
{
[JsonProperty("testsystem")]
public string testsystem { get; set; }
[JsonProperty("playback")]
public pb playback { get; set; }
}
public class pb
{
[JsonProperty("playback")]
public int playback { get; set; }
//[JsonProperty("cue")]
public cue cue { get; set; }
}
public class cue
{
[JsonProperty("cue")]
public string number { get; set; }
[JsonProperty("state")]
public string state { get; set; }
[JsonProperty("label")]
public string label { get; set; }
}
My class declarations
Company thisCompany = new Company
{
testsystem = "1.0.0",
for (PB = 1; PB < 7; PB++)
{
playback = new pb
{
cue = new cue
{
number = Globals.QNumber[1],
state = Globals.QState[1],
label = Globals.QLabel[1]
}
}
}
string json = JsonConvert.SerializeObject(thisCompany);
The section of code im trying to serialise
So my first issue is that I cant figure out how to have the "playback" sections nested so that there are 2 as in the example. I tried adding a for loop but (shown in my code above) but that seems to take the playback = new pb line out of context?
The 2nd issue is that i wind up with a double "playback section shown in the output below (i took the for loop out to get this bit to work)
{
"testsystem": "1.0.0",
"playback": {
"playback": 0,
"cue": {
"cue": "34",
"state": "Running",
"label": "Hello World"
}
}
}
I feel like this must be simple but im just missing the simplest thing and overthinking. Thanks in advance for any thoughts and suggestions.
2
Answers
I don’t think your model is quite fits the example json. It should look more like this with your "playback" object being a dictionary:
Then you can create the object and serialize them like so:
Which will generate the json that’s formatted like your sample:
if you need only a json string , you don’t need any classes