Baklava12 Baklava12 - 3 years ago 73
C# Question

Serializing JSON Object Array (Json.NET)

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


Here is what my C# classes looks like

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


So far, I have tried coding it like this, similar to how the examples are on the newtonsoft website

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


but I'm getting two CS0117 errors at

Grocery = new Grocery


and

Department = new Department


which says that
Store
does not contain a definition for
Grocery
/
Department


What am I doing wrong here? Did I just make an error in syntax or is there a possibility I am just approaching serializing this the wrong way? Much thanks in advance for your guy's help.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download