How to convert Enum to Json object with Header in C# - c#

Here's what I've done so far
public enum TCountryNames
{
[Display(Name="America")]
cnUSA = 1,
[Display(Name="England")]
cnUK,
[Display(Name="CHINA")]
cnCHN
}
public class MyClass
{
public static List<KeyValuePair<string, int>> GetEnumList()
{
var list = new List<KeyValuePair<string, int>>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new KeyValuePair<string, int>(e.ToString(), (int)e));
}
return list;
}
}
Result: [cnUSA,1] with total count 3 and without header
The result i want is [{"Id":1,"Name":"America"},{"Id":2,"Name":"England"}]
I've tried [JsonConverter(typeof(StringEnumConverter))]
public TCountryNames Names{ get; set; }
I've also tried converting enum to array list var names = Enum.GetValues(typeof(TCountryNames));
ArrayList arrLst = new ArrayList() { names };
but both of them doesn't seems to be working.
*Any help will be appreciated. Thank You in Advance. *

If you don't want to add new class
public static List<Dictionary<string, object>> GetEnumList()
{
var list = new List<Dictionary<string, object>>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new Dictionary<string, object> { { "Id", (int)e }, { "Name", e.ToString() } });
}
return list;
}
Define a model for serialization
public class EnumData
{
public int Id { get; set; }
public string Name { get; set; }
}
public static List<EnumData> GetEnumList()
{
var list = new List<EnumData>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new EnumData { Id = (int)e, Name = e.ToString() });
}
return list;
}

For get display name value you should use System.Reflection. And then you could do this in simple way:
public enum TCountryNames
{
[Display(Name = "America")]
cnUSA = 1,
[Display(Name = "England")]
cnUK,
[Display(Name = "CHINA")]
cnCHN
}
public class EnumData
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class MyClass
{
public static List<EnumData> GetEnumList()
{
var list = new List<EnumData>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new EnumData
{
Id = (int)e,
Name = e.GetType()
.GetMember(e.ToString())
.First()?
.GetCustomAttribute<DisplayAttribute>()?
.GetName()
});
}
return list;
}
}
So to clarify:
you create loop foreach enum
take id by casting
take name using reflaction - I added all needed protection against null exception
Output:
[
{
"Id": 1,
"Name": "America"
},
{
"Id": 2,
"Name": "England"
},
{
"Id": 3,
"Name": "CHINA"
}
]
Example: https://dotnetfiddle.net/XVL2LI

Related

Format each list entry with name JSON

I'm trying to format a List object to JSON in a specific way:
...
{
"MyList": [
"Entry": {
"Id": "1000",
"Name" : "Billy"
}
]
}
...
My problem is that I can't get the "Entry" property name to be written per item in the list.
Here's my C# code:
Entry.cs
[JsonObject(MemberSerialization.OptIn)]
public class Entry
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string Name { get; set; }
}
List.cs
[JsonObject(MemberSerialization.OptIn)]
public class MyList
{
[JsonProperty]
List<Entry> List = new List<Entry>();
public void Add(Entry param) {
List.Add(param);
}
}
TestController.cs
[HttpPost]
public IHttpActionResult GrabarMarcacion([FromBody] JObject data)
{
MyList lst = new MyList();
lst.Add(new Entry{Id="1000", Name="Billy"});
return Ok(lst);
}
I'm sorry I'm new to JSON and REST, is it even possible to do what I ask? so far I always get something like:
{
"List": {
{
"ID": "1000",
"Name" : "Billy"
},
{
"ID": "1001",
"Name" : "Bob"
}
}
}
I have never used c# but try for Entry.cs :
[JsonObject(MemberSerialization.OptIn)]
public class Entry
{
[JsonProperty]
public object Entry { get; set; }
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string Name { get; set; }
}
}
From what I understand, you want Entry property name for every item in the list. The simplest way to do this would be by making it a Dictionary:
Renamed Entry.cs to EntryModel.cs
[JsonObject(MemberSerialization.OptIn)]
public class EntryModel
{
[JsonProperty]
public Dictionary<string, string> Entry { get; set; }
}
In List.cs, change the property to MyList. This requires a change to the class name.
[JsonObject(MemberSerialization.OptIn)]
public class MyListModel
{
[JsonProperty]
public List<EntryModel> MyList { get; set; } = new List<EntryModel>();
}
Now in your TestController.cs, you may use:
MyListModel lst = new MyListModel();
lst.MyList.Add(new EntryModel
{
Entry = new Dictionary<string, string> {
{ "Id", "1000" }, { "Name", "Billy" } }
});
lst.MyList.Add(new EntryModel
{
Entry = new Dictionary<string, string> {
{ "Id", "3000" }, {"Name", "ABC" } }
});
This gives the following JSON:
{
"MyList": [
{
"Entry": {
"Id": "1000",
"Name": "Billy"
}
},
{
"Entry": {
"Id": "3000",
"Name": "ABC"
}
}
]
}

Loop for add a json for each object in list

I'm making a tool that needs to export a json. He needs to be in this format:
{
"version" : "2",
"mangas" : [ {
"manga" : [ "sample", "manganame", 1234567890, 0, 0 ],
"chapters" : [ {
"u" : "urlexample",
"r" : 1
}, {
"u" : "urlexample",
"r" : 1
}, {
"u" : "urlexample",
"r" : 1
} ]
} ]
}
And this is my code:
void createJson(String manganame, String mangaoid, String sourceid)
{
String[] mangainfo = { "/manga/" + mangaoid, manganame, sourceid, "0", "0" };
var root = new RootObject()
{
version = "2",
mangas = new List<Manga>()
{
new Manga()
{
manga = mangainfo,
chapters = new List<Chapter>()
{
new Chapter
{
u = "sample",
r = 1
}
}
}
}
};
var json = JsonConvert.SerializeObject(root);
File.WriteAllText(#"D:\path.txt", json);
Console.WriteLine(json);
}
I'm lost, if someone can help me. Already give a search on Google, but the answer didn't come up in my head, already trying for a few time, slowly I'm getting but now is time to ask for help lol
For the list I was talking about, I'll explain it. I have a sqlite DB that have various information from mangas etc... I execute a query where I filter by a id, "SELECT * FROM MangaChapter WHERE manga_id = 'someid'", then i put the result on a list using a for loop. In the DB chapter url is stored like that "mr-chapter-166165" this is why i have had to concat string in chapterList.add.
List<String> chapterList = new List<String>();
cmd.CommandText = "SELECT * FROM MangaChapter WHERE manga_id = '3252'";
reader = cmd.ExecuteReader();
while (reader.Read())
{
chapterList.Add("/pagesv2?oid=" + reader.GetString("oid"));
}
For reference this is what I'm using to manage the sqlite db https://www.nuget.org/packages/dotConnect.Express.for.SQLite/
In the list, each chapter is something like that "/pagesv2?oid=mr-chapter-166165", if I print all the list on the console we'll be having something like that:
/pagesv2?oid=mr-chapter-166165
/pagesv2?oid=mr-chapter-166166
/pagesv2?oid=mr-chapter-166167
Here are the classes I generated from the given JSON sample
public class Chapter
{
[JsonProperty("u")]
public string U { get; set; }
[JsonProperty("r")]
public int R { get; set; }
}
public class Manga
{
[JsonProperty("manga")]
public IList<object> MangaInfos { get; set; }
[JsonProperty("chapters")]
public IList<Chapter> Chapters { get; set; }
}
public class Example
{
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("mangas")]
public IList<Manga> Mangas { get; set; }
}
and here the code to reproduce the give JSON sample
var d = new Example
{
Version = "2",
Mangas = new List<Manga>
{
new Manga()
{
MangaInfos = new List<object>{ "sample", "manganame", 1234567890, 0, 0 },
Chapters = new List<Chapter>
{
new Chapter()
{
U = "urlexample",
R = 1,
},
new Chapter()
{
U = "urlexample",
R = 1,
},
new Chapter()
{
U = "urlexample",
R = 1,
},
},
},
},
};
var json = JsonConvert.SerializeObject(d,Formatting.Indented);
Console.WriteLine(json);
The output looks like
{
"version": "2",
"mangas": [
{
"manga": [
"sample",
"manganame",
1234567890,
0,
0
],
"chapters": [
{
"u": "urlexample",
"r": 1
},
{
"u": "urlexample",
"r": 1
},
{
"u": "urlexample",
"r": 1
}
]
}
]
}
and live view at .net fiddle
Based on your comment, if you want to have various chapters for each "Manga", you have to change your data structure and that changes the Result Json you want.
maybe something like this?
public partial class Root
{
public long Version { get; set; }
public Mangas[] Mangas { get; set; }
}
public partial class Mangas
{
public Manga[] Manga { get; set; }
}
public partial class Chapter
{
public string U { get; set; }
public long R { get; set; }
}
public partial struct Manga
{
public long? Integer;
public string String;
public Chapter[] Chapters { get; set; }
}
Iterate through chapters. Solution below.
class Parent
{
public int Version { get; set; }
public List<Manga> mangas { get; set; }
}
class Manga
{
public List<object> manga { get; set; }
public List<Chapter> chapters { get; set; }
}
class Chapter
{
public string u { get; set; }
public int r { get; set; }
}
void createJson(String manganame, string mId, String mangaoid, long sourceid)
{
var json = new Parent()
{
Version = 2,
mangas = new List<Manga>()
{
new Manga()
{
manga = new List<object>{ "/manga/"+mangaoid, manganame, sourceid, 0, 0 },
chapters = Chapters(),
}
}
};
var sjson = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText(#"C:\Users\Izurii\Desktop\oi.json", sjson);
}
List<Chapter> Chapters()
{
List<Chapter> chapters = new List<Chapter>();
for(int i = 0; i < links.Count; i ++)
{
chapters.Add(
new Chapter()
{
u = links[i],
r = 1,
});
}
return chapters;
}

How to receive JSON data in Dictionary using FromData in Web api?

Below is JSON example which client will send to my API named as 'GetQuestion'
{
"lstQuestions": [{
"QuestionCategory": 1,
"QuestionText": "what is m in mvc",
"OptionA": "model",
"OptionB": "view",
"OptionC": "controller",
"OptionD": "razor",
"CorrectOption": "A"
},
{
"QuestionCategory": 2,
"QuestionText": "How are you",
"OptionA": "fine",
"OptionB": "not fine",
"OptionC": "ok",
"OptionD": "not ok",
"CorrectOption": "A"
}],
"Status" : 1
}
Below is my controller API code:
public class QuestionDetails
{
public List<Questions> lstQuestions { get; set; }
public int Status { get; set; }
}
public class Questions
{
public string QuestionCategory { get; set; }
public string QuestionText { get; set; }
public string OptionA { get; set; }
public string OptionB { get; set; }
public string OptionC { get; set; }
public string OptionD { get; set; }
public string CorrectOption { get; set; }
}
[Route("GetQuestions")]
[HttpPost]
public HttpResponseMessage SendQuestionDetails([FromBody] QuestionDetails UserDetailInput)
{
HttpResponseMessage mesage = Request.CreateResponse(HttpStatusCode.OK, "Demo"); ;
if (ModelState.IsValid)
{
//in progress
}
return mesage;
}
What I want to do is how to create a class with Dictionary and pass as parameter, I don't want to use List because its heavy and Dictionary is much faster than List.
For example:
public class QuestionDetails
{
public Dictionary<string, Questions> lstQuestions { get; set; }
public int Status { get; set; }
}
public HttpResponseMessage SendQuestionDetails([FromBody] Dictionary<string, QuestionDetails> UserDetailInput)
{
HttpResponseMessage mesage = Request.CreateResponse(HttpStatusCode.OK, "Demo"); ;
if (ModelState.IsValid)
{
//in progress
}
return mesage;
}
Don't know what are you talking about with Dictionary is much faster than List but you just need to send the JSON as
{
"A": {
"lstQuestions": {
"A": {
"QuestionCategory": 1,
"QuestionText": "what is m in mvc",
"OptionA": "model",
"OptionB": "view",
"OptionC": "controller",
"OptionD": "razor",
"CorrectOption": "A"
},
"V": {
"QuestionCategory": 2,
"QuestionText": "How are you",
"OptionA": "fine",
"OptionB": "not fine",
"OptionC": "ok",
"OptionD": "not ok",
"CorrectOption": "A"
}
},
"Status": 1
}
}
Hope below code will clear your query.
public HttpResponseMessage SendQuestionDetails([FromBody] Dictionary<string, QuestionDetails> UserDetailInput)
{
List<Questions> list = new List<Questions> { };
list.Add(new Questions
{
CorrectOption = "CorrectOption1",
OptionA = "OptionA1",
OptionB = "OptionB1",
OptionC = "OptionC1",
OptionD = "OptionD1",
QuestionCategory = "QuestionCategory1",
QuestionText = "QuestionText1"
});
list.Add(new Questions
{
CorrectOption = "CorrectOption2",
OptionA = "OptionA2",
OptionB = "OptionB2",
OptionC = "OptionC2",
OptionD = "OptionD2",
QuestionCategory = "QuestionCategory2",
QuestionText = "QuestionText2"
});
Dictionary<QuestionDetails, int> dictionary = new Dictionary<QuestionDetails, int> { };
QuestionDetails detail = new QuestionDetails { lstQuestions = list, Status = 1 };
HttpResponseMessage mesage = Request.CreateResponse(HttpStatusCode.OK, detail);
return mesage;
return mesage;
}

How can I create a JsonPatchDocument from comparing two c# objects?

Given I have two c# objects of the same type, I want to compare them to create a JsonPatchDocument.
I have a StyleDetail class defined like this:
public class StyleDetail
{
public string Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal OriginalPrice { get; set; }
public decimal Price { get; set; }
public string Notes { get; set; }
public string ImageUrl { get; set; }
public bool Wishlist { get; set; }
public List<string> Attributes { get; set; }
public ColourList Colours { get; set; }
public SizeList Sizes { get; set; }
public ResultPage<Style> Related { get; set; }
public ResultPage<Style> Similar { get; set; }
public List<Promotion> Promotions { get; set; }
public int StoreStock { get; set; }
public StyleDetail()
{
Attributes = new List<string>();
Colours = new ColourList();
Sizes = new SizeList();
Promotions = new List<Promotion>();
}
}
if I have two StyleDetail objects
StyleDetail styleNew = db.GetStyle(123);
StyleDetail styleOld = db.GetStyle(456);
I now want to create a JsonPatchDocument so I can send the differences to my REST API... How to do this??
JsonPatchDocument patch = new JsonPatchDocument();
// Now I want to populate patch with the differences between styleNew and styleOld - how?
in javascript, there is a library to do this https://www.npmjs.com/package/rfc6902
Calculate diff between two objects:
rfc6902.createPatch({first: 'Chris'}, {first: 'Chris', last:
'Brown'});
[ { op: 'add', path: '/last', value: 'Brown' } ]
but I am looking for a c# implementation
Let's abuse the fact that your classes are serializable to JSON!
Here's a first attempt at a patch creator that doesn't care about your actual object, only about the JSON representation of that object.
public static JsonPatchDocument CreatePatch(object originalObject, object modifiedObject)
{
var original = JObject.FromObject(originalObject);
var modified = JObject.FromObject(modifiedObject);
var patch = new JsonPatchDocument();
FillPatchForObject(original, modified, patch, "/");
return patch;
}
static void FillPatchForObject(JObject orig, JObject mod, JsonPatchDocument patch, string path)
{
var origNames = orig.Properties().Select(x => x.Name).ToArray();
var modNames = mod.Properties().Select(x => x.Name).ToArray();
// Names removed in modified
foreach (var k in origNames.Except(modNames))
{
var prop = orig.Property(k);
patch.Remove(path + prop.Name);
}
// Names added in modified
foreach (var k in modNames.Except(origNames))
{
var prop = mod.Property(k);
patch.Add(path + prop.Name, prop.Value);
}
// Present in both
foreach (var k in origNames.Intersect(modNames))
{
var origProp = orig.Property(k);
var modProp = mod.Property(k);
if (origProp.Value.Type != modProp.Value.Type)
{
patch.Replace(path + modProp.Name, modProp.Value);
}
else if (!string.Equals(
origProp.Value.ToString(Newtonsoft.Json.Formatting.None),
modProp.Value.ToString(Newtonsoft.Json.Formatting.None)))
{
if (origProp.Value.Type == JTokenType.Object)
{
// Recurse into objects
FillPatchForObject(origProp.Value as JObject, modProp.Value as JObject, patch, path + modProp.Name +"/");
}
else
{
// Replace values directly
patch.Replace(path + modProp.Name, modProp.Value);
}
}
}
}
Usage:
var patch = CreatePatch(
new { Unchanged = new[] { 1, 2, 3, 4, 5 }, Changed = "1", Removed = "1" },
new { Unchanged = new[] { 1, 2, 3, 4, 5 }, Changed = "2", Added = new { x = "1" } });
// Result of JsonConvert.SerializeObject(patch)
[
{
"path": "/Removed",
"op": "remove"
},
{
"value": {
"x": "1"
},
"path": "/Added",
"op": "add"
},
{
"value": "2",
"path": "/Changed",
"op": "replace"
}
]
You could use my DiffAnalyzer. It's based on reflection and you can configure the depth you want to analyze.
https://github.com/rcarubbi/Carubbi.DiffAnalyzer
var before = new User { Id = 1, Name="foo"};
var after= new User { Id = 2, Name="bar"};
var analyzer = new DiffAnalyzer();
var results = analyzer.Compare(before, after);
You can use this
You can install using NuGet, see SimpleHelpers.ObjectDiffPatch at NuGet.org
PM> Install-Package SimpleHelpers.ObjectDiffPatch
Use:
StyleDetail styleNew = new StyleDetail() { Id = "12", Code = "first" };
StyleDetail styleOld = new StyleDetail() { Id = "23", Code = "second" };
var diff = ObjectDiffPatch.GenerateDiff (styleOld , styleNew );
// original properties values
Console.WriteLine (diff.OldValues.ToString());
// updated properties values
Console.WriteLine (diff.NewValues.ToString());

Appending to JSON object using JSON.net

I need to serialize a JSON object that looks like this:
{
"Documents": [
{
"Title": "",
"DatePublished": "",
"DocumentURL": "",
"ThumbnailURL": "",
"Abstract": "",
"Sector": "",
"Country": [
"", "", ""
],
"Document Type": ""
}
]
}
What I'm doing is taking the data from SQL server and storing the results into an object like this:
public List<Dictionary<string, string>> GetResults()
{
int index = 0;
while (this.myReader.Read())
{
this.dataFrmDb = new Dictionary<string, string>();
for (int i = 0; i < myReader.FieldCount; i++)
{
if (myReader.GetName(i) == "Country")
{
string[] delimiter = { " _qfvcq_ " };
string text = myReader[myReader.GetName(i)].ToString();
string[] results = text.Split(delimiter, StringSplitOptions.None);
//This list stores the values for "Country".
List<string> countries = new List<string>();
for (int j = 0; j < results.Count(); j++)
{
countries.Add(results[j].ToString());
}
}
else
{
this.dataFrmDb.Add(myReader.GetName(i),
myReader[myReader.GetName(i)].ToString());
}
}
this.dictList.Add(this.dataFrmDb);
}
return this.dictList;
}
I then take this data and serialize like this:
Database connect = new Database(
System.Configuration.ConfigurationManager.AppSettings["DatabaseConnectionString"],
System.Configuration.ConfigurationManager.AppSettings["StoredProcedure"]);
List<Dictionary<string, string>> dataResults = connect.GetResults();
Dictionary<string, List<Dictionary<string, string>>> myList =
new Dictionary<string, List<Dictionary<string, string>>>();
myList.Add("Documents", dataResults);
string ans = JsonConvert.SerializeObject(myList, Formatting.Indented);
System.Console.WriteLine(ans);
I get the proper output but if you would look in the original JSON format, "Country" needs to have multiple values. I don't know how to implement that into this JSON object. How do I add a list with the "Country" values to the JSON object using JSON.net? Is there another way to go about this?
If you change dataFrmDb to be Dictionary<string, object> instead of a Dictionary<string, string>, then you can store the Countries list into it like the other values. Json.Net will then serialize it like you want.
Here is an example program which demonstrates:
class Program
{
static void Main(string[] args)
{
List<Dictionary<string, object>> dataResults = GetResults();
Dictionary<string, List<Dictionary<string, object>>> myList =
new Dictionary<string, List<Dictionary<string, object>>>();
myList.Add("Documents", dataResults);
string ans = JsonConvert.SerializeObject(myList, Formatting.Indented);
System.Console.WriteLine(ans);
}
public static List<Dictionary<string, object>> GetResults()
{
List<Dictionary<string, object>> dictList = new List<Dictionary<string, object>>();
Dictionary<string, object> dataFrmDb = new Dictionary<string, object>();
dataFrmDb.Add("Title", "An Example Document");
dataFrmDb.Add("DatePublished", DateTime.Now.ToString());
dataFrmDb.Add("DocumentURL", "http://www.example.org/documents/1234");
dataFrmDb.Add("ThumbnailURL", "http://www.example.org/thumbs/1234");
dataFrmDb.Add("Abstract", "This is an example document.");
dataFrmDb.Add("Sector", "001");
dataFrmDb.Add("Country", new List<string> { "USA", "Bulgaria", "France" });
dataFrmDb.Add("Document Type", "example");
dictList.Add(dataFrmDb);
return dictList;
}
}
Output:
{
"Documents": [
{
"Title": "An Example Document",
"DatePublished": "4/9/2013 7:25:05 PM",
"DocumentURL": "http://www.example.org/documents/1234",
"ThumbnailURL": "http://www.example.org/thumbs/1234",
"Abstract": "This is an example document.",
"Sector": "001",
"Country": [
"USA",
"Bulgaria",
"France"
],
"Document Type": "example"
}
]
}
A somewhat more straightforward way to do it is to create separate classes to hold the data, as was suggested by Joey Gennari. Json.NET can serialize those as well. The data classes would look something like this:
class Result
{
public List<Document> Documents { get; set; }
public Result()
{
Documents = new List<Document>();
}
}
class Document
{
public string Title { get; set; }
public string DatePublished { get; set; }
public string DocumentURL { get; set; }
public string ThumbnailURL { get; set; }
public string Abstract { get; set; }
public string Sector { get; set; }
public List<string> Country { get; set; }
[JsonProperty(PropertyName="Document Type")]
public string DocumentType { get; set; }
public Document()
{
Country = new List<string();
}
}
And here is the usage:
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
doc.Title = "An Example Document";
doc.DatePublished = DateTime.Now.ToString();
doc.DocumentURL = "http://www.example.org/documents/1234";
doc.ThumbnailURL = "http://www.example.org/thumbs/1234";
doc.Abstract = "This is an example document.";
doc.Sector = "001";
doc.Country.Add("USA");
doc.Country.Add("Bulgaria");
doc.Country.Add("France");
doc.DocumentType = "example";
Result result = new Result();
result.Documents.Add(doc);
string json = JsonConvert.SerializeObject(result, Formatting.Indented);
System.Console.WriteLine(json);
}
}
The output for this example is exactly the same as the first.
Here is a different way to solve it with DataContractJsonSerializer. First create a class to represent the object:
[DataContract]
public class DocumentHolder
{
[DataMember(Name = "Documents")]
public Documents Document { get; set; }
}
[DataContract]
public class Documents
{
[DataMember(Name = "Title", Order = 1)]
public string Title { get; set; }
[DataMember(Name = "DatePublished", Order = 2)]
public DateTime? DatePublished { get; set; }
[DataMember(Name = "DocumentURL", Order = 3)]
public string DocumentURL { get; set; }
[DataMember(Name = "ThumbnailURL", Order = 4)]
public string ThumbnailURL { get; set; }
[DataMember(Name = "Abstract", Order = 5)]
public string Abstract { get; set; }
[DataMember(Name = "Sector", Order = 6)]
public string Sector { get; set; }
[DataMember(Name = "Country", Order = 7)]
public List<string> Country { get; set; }
[DataMember(Name = "Document Type", Order = 8)]
public string DocumentType { get; set; }
public Documents()
{
this.Country = new List<string>();
}
}
Here's how you would fill the object and serialize it:
static void Main(string[] args)
{
var documentholder = new DocumentHolder { Document = new Documents { Title = "Title 1", DatePublished = DateTime.Now, Sector = "A17", Country = new List<string> { "EN-US", "EN-GB" } } };
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DocumentHolder));
var ms = new MemoryStream();
serializer.WriteObject(ms, documentholder);
var text = Encoding.UTF8.GetString(ms.ToArray());
}

Categories