Allen Jones
Allen Jones

Reputation: 47

JSON from List in C#

I have a List in an MVC app that contains 141 entries. How do I create a JSON from that list and add other properties to it. I am currently trying the following but I get an error on the second iteration stating that the property already exists:

dynamic jsonOb = new JObject();

foreach(var titles in titleList)
{
    jsonOb.Add("TitleNumber", titles.ToString());
    jsonOb.Add("ProjectID", projid.ToString());
    jsonOb.Add("AddedBy", user);
    jsonOb.Add("DateAdded", Convert.ToString(DateTime.Now));
}

Upvotes: 0

Views: 105

Answers (3)

Dipo
Dipo

Reputation: 132

When you open up your visual studio, check => tools => Nuget Package Manager => Manage Nuget Package for solutions.

Go to the browse tab and search for 'Newtonsoft.Json'(without the quotes).

Once installed, import the namespace in your class and:

var convertedResult = JsonConvert.SerializeObject(titleList);

Easier that way.

Upvotes: 0

Rey
Rey

Reputation: 4002

You can usee JsonConvert.SerializeObject(myObject) as well from Newtonsoft.Json package. Here is the doc for this.

var result = JsonConvert.SerializeObject(titleList);

If you don`t have it installed you can get it from nuget package manager.

Upvotes: 1

Selman Genç
Selman Genç

Reputation: 101681

You need a JArray:

var jsonArr = new JArray();

 foreach(var titles in titleList)
 {
     var jsonOb = new JObject();
     jsonOb.Add("TitleNumber", "foo");
     jsonOb.Add("ProjectID", "foo");
     jsonOb.Add("AddedBy", "foo");
     jsonOb.Add("DateAdded", "foo");
     jsonArr.Add(jsonOb);
}

Btw since you are using JSON.NET already, SerializeObject method is easier and more straightforward than creating objects manually, so I suggest using that.

Upvotes: 3

Related Questions