I'm learning JSON and was wondering how to create an array of objects. I want my JSON file to look like this
{
"Place": {
"Stores": [{
"Grocery": {
"stock": "fruit",
"distance": 19,
"size": 12
},
"Department": {
"stock": "clothing",
"distance": 21,
"size": 7
}
}]
}
}
public class RootObject
{
public Place Place { get; set; }
}
public class Place
{
public List<Store> Stores { get; set; }
}
public class Store
{
public Grocery Grocery { get; set; }
public Department Department { get; set; }
}
public class Grocery
{
public string stock { get; set; }
public int distance { get; set; }
public int size { get; set; }
}
public class Department
{
public string stock { get; set; }
public int distance { get; set; }
public int size { get; set; }
}
Rootobject root = new Rootobject
{
Place = new Place
{
stores = new List<Store>
{
Grocery = new Grocery
{
stock ="fruit",
distance = 19,
size = 12
},
Department = new Department
{
stock ="clothing",
distance = 21,
size = 7
}
}
}
};
string json = JsonConvert.SerializeObject(root,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\output.json", json);
Grocery = new Grocery
Department = new Department
Store
Grocery
Department
Your object should look like this:
Rootobject root = new Rootobject
{
Place = new Place
{
stores = new List<Store>
{
new Store{
Grocery = new Grocery
{
stock ="fruit",
distance = 19,
size = 12
},
Department = new Department
{
stock ="clothing",
distance = 21,
size = 7
}
}
}
}
};
I wrote it from my head, so I hope syntax is good. But main idea is that you were creating list of stores and not any store inside that list. You should create some Store using new Store