Create JSON with dynamic using newtonsoft json.net - c#

I am trying to create or searealize json in this format
{
"title": "Star Wars",
"link": "http://www.starwars.com",
"description": "Star Wars blog.",
"item": [
{
"title": "Episode VII",
"description": "Episode VII production",
"link": "episode-vii-production.aspx"
},
{
"title": "Episode VITI",
"description": "Episode VII production",
"link": "episode-vii-production.aspx"
}
]
}
i am trying this achieve this
dynamic o = new ExpandoObject();
o.title= "fdsfs";
o.link= "fsrg";
o.description="fdsfs";
foreach (var adata in all)
{
o.item.title="fgfd";
o.item.description="sample desc";
o.item.link="http://google.com"
}
string json = JsonConvert.SerializeObject(o);
but than here it throws exception on foreach loop on item it tells it does not contain defination for the same etc .so what i am doing wrong and how to achieve the same

That is the construction you should have to get the json you've stated. The problem with your code is that item should be actually a list of items.
public class Item
{
public string title { get; set; }
public string description { get; set; }
public string link { get; set; }
}
public class RootObject
{
public string title { get; set; }
public string link { get; set; }
public string description { get; set; }
public List<Item> item { get; set; }
}
Then you ca use this code:
dynamic o = new ExpandoObject();
o.title= "fdsfs";
o.link= "fsrg";
o.description="fdsfs";
o.item = new List<ExpandoObject>();
//although list of dynamics is not recommended as far as I remember
foreach (var adata in all)
{
o.item.Add(new Item(){
title="fgfd",
description="sample desc",
link="http://google.com" });
}
string json = JsonConvert.SerializeObject(o);

You have to create o.item to assign values into it:
dynamic o = new ExpandoObject();
var all = new object[] { new object() };
o.title= "fdsfs";
o.link= "fsrg";
o.description="fdsfs";
var items = new List<ExpandoObject>();
foreach (var adata in all)
{
dynamic item = new ExpandoObject();
item.title="fgfd";
item.description="sample desc";
item.link="http://google.com";
items.Add(item);
}
o.item = items;
string json = JsonConvert.SerializeObject(o);

Related

How to convert json with dynamic root name to C# list

var stringResult = await HttpHelper.PostAsync(batchUrl, content);
I am getting following result as an API response in C# in above stringResult variable after calling above line. I want to convert below "Items" value to C# list. In every result, first GUID is different. How to convert the below result in C# List. I want only Items.
{
"0934009e-6518-4440-91e3-c252d2e2cc4f": {
"Status": 200,
"Headers": {
"Content-Type": "application/json; charset=utf-8"
},
"Content": {
"Items": [{
"Timestamp": "2021-10-18T14:00:00Z",
"Value": 20.7,
"UnitsAbbreviation": "ppm"
}, {
"Timestamp": "2021-10-25T14:00:00Z",
"Value": 15.9,
"UnitsAbbreviation": "ppm"
}, {
"Timestamp": "2021-11-01T14:00:00Z",
"Value": 14.8,
"UnitsAbbreviation": "ppm"
}, {
"Timestamp": "2021-11-08T15:00:00Z",
"Value": 20.1,
"UnitsAbbreviation": "ppm"
}, {
"Timestamp": "2021-11-15T15:00:00Z",
"Value": 19.5,
"UnitsAbbreviation": "ppm"
}, {
"Timestamp": "2021-11-22T15:00:00Z",
"Value": 19.7,
"UnitsAbbreviation": "ppm"
}, {
"Timestamp": "2021-11-29T15:00:00Z",
"Value": 20.4,
"UnitsAbbreviation": "ppm"
}
]
}
}
}
When some part of the json structure is unknown, you need to explore it manually. There are several ways to do it, but I'm used to passing JObject :
var root = JObject.Parse(text);
// Unknown name property, then iterate
// When the object has one property, First is a good fit
var response = root.First as JProperty;
var guid = response.Name;
var itemsJson = response.Value["Content"]["Items"];
var items = itemsJson.ToObject<List<Item>>();
you can try this code
List<Item> items = JObject.Parse(stringResult).Properties()
.First().Value["Content"]["Items"].ToObject<List<Item>>();
public class Item
{
public DateTime Timestamp { get; set; }
public double Value { get; set; }
public string UnitsAbbreviation { get; set; }
}
go to https://json2csharp.com/
convert your json to C# class.
since your root node is dynamic guid, you cannot directly use class structure deserialization but you can use a inner nodes
Pseudo Program
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
WebClient w = new WebClient();
string json = w.DownloadString(new Uri("https://jsonkeeper.com/b/GETO"));
var firstObject = JObject.Parse(json);
var guid = firstObject.Properties().Select(p => p.Name).FirstOrDefault();
//Console.Write(guid);
Root output = firstObject[guid].ToObject<Root>();
Console.Write(output.Content.Items.Count());
The DTO structure
public class Root
{
public int Status { get; set; }
public Headers Headers { get; set; }
public Content Content { get; set; }
}
public class Content
{
public List<Item> Items { get; set; }
}
public class Headers
{
[JsonProperty("Content-Type")]
public string ContentType { get; set; }
}
public class Item
{
public DateTime Timestamp { get; set; }
public double Value { get; set; }
public string UnitsAbbreviation { get; set; }
}
here's fiddle: https://dotnetfiddle.net/w5fO0w
I have used below code to get items -
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array )
.Children<JObject>();
foreach (JObject result in resultObjects)
{
foreach (JProperty property in result.Properties())
{
}
}
And method is -
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}

C# model for nested properties

I need to make API request to CloudFlare to purge cache of individual files.
Can someone please guide how to represent the below as C# model class.
files: [
"http://www.example.com/css/styles.css",
{
"url": "http://www.example.com/cat_picture.jpg",
"headers": {
"Origin": "cloudflare.com",
"CF-IPCountry": "US",
"CF-Device-Type": "desktop"
}
}
]
var obj = new
{
files = new object[]
{
"http://www.example.com/css/styles.css",
new
{
url = "http://www.example.com/cat_picture.jpg",
headers = new Dictionary<string,string>
{
{ "Origin", "cloudflare.com" },
{ "CF-IPCountry","US" },
{ "CF-Device-Type", "desktop"}
}
}
}
};
The dictionary is there because of the awkward property names like CF-IPCountry which make it not possible to use an anonymous type.
To show it working:
var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Formatting.Indented);
gives:
{
"files": [
"http://www.example.com/css/styles.css",
{
"url": "http://www.example.com/cat_picture.jpg",
"headers": {
"Origin": "cloudflare.com",
"CF-IPCountry": "US",
"CF-Device-Type": "desktop"
}
}
]
}
Edit; that's not quite right - the dictionary didn't work, but I don't have time to fix it.
Using classes (maybe you could use better class names then mine :) ):
class Root
{
[JsonProperty(PropertyName = "files")]
public List<object> Files { get; set; } = new List<object>();
}
class UrlContainer
{
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "headers")]
public Headers Headers { get; set; }
}
class Headers
{
public string Origin { get; set; }
[JsonProperty(PropertyName = "CF-IPCountry")]
public string CfIpCountry { get; set; }
[JsonProperty(PropertyName = "CF-Device-Type")]
public string CfDeviceType { get; set; }
}
Usage
var root = new Root();
// Add a simple url string
root.Files.Add("http://www.example.com/css/styles.css");
var urlContainer = new UrlContainer() {
Url = "http://www.example.com/cat_picture.jpg",
Headers = new Headers()
{
Origin = "cloudflare.com",
CfIpCountry = "US",
CfDeviceType = "desktop"
}
};
// Adding url with headers
root.Files.Add(urlContainer);
string json = JsonConvert.SerializeObject(root);
Note: I'm using Newtonsoft.Json

How to create hierarchy in json string from string array?

I am trying to generate json string for the hierarchy like below:
Company(select * from Company)
Department(select * from Department)
Employee(select * from Employee)
Each of the above query will return fields like below:
Company Fields - (Id,Name,Location)
Department Fields - (Id,Name,CompanyId)
Employee Fields - (Id,Name,DepartmentId)
Now I am trying to generate JSON string for above entities like below:
Expected output:
{
"Id": "",
"Name": "",
"Location": "",
"Department":
{
"Id": "",
"Name": "",
"CompanyId": "",
"Employee" :
{
"Id": "",
"Name": "",
"DepartmentId": "",
}
}
}
Code:
public string GetData(Child model,List<Parent> parents)
{
var fields = new List<string[]>();
if (parents != null)
{
foreach (var parent in parents)
{
var columns = GetColumns(parent); //returns string[] of columns
fields.Add(columns);
}
}
fields.Add(GetColumns(model));
string json = JsonConvert.SerializeObject(fields.ToDictionary(key => key, v => string.Empty),
Formatting.Indented);
return json;
}
Now when I don't have any parents and want to generate json string for only child then below code is working fine:
string json = JsonConvert.SerializeObject(fields.ToDictionary(key => key, v => string.Empty),Formatting.Indented)
Output :
{
"Id": "",
"Name": "",
"Location": "",
}
But now I want to generate JSON for my hierarchy with any such inbuilt way.
I know I can loop,append and create json string but I want to do this in better way like I have done for my child.
Update:
public class Child
{
public string Name { get; set; } // Contains Employee
//Other properties and info related to process sql query and connection string
}
public class Parent
{
public string Name { get; set; } // Contains Company,Department.
public string SqlQuery { get; set; } // query related to Company and Department.
//Other properties and info related to connection string
}
I created a class that holds the Information similarly to what you proposed, in a child-parent structure. I also added a custom little Parser that works recursively. Maybe that's what you need and/or what gives you the ideas you need to fix your problem.
I also altered the output a little bit, by adding the angled brackets ( "[ ]" ). I think that's what you will need with multiple children. At least that's what the JSON validator tells me that I posted below. If you don't need/ want them, just remove them in the parser.
I don't think you can use the parser you used in your example without having some form of extra fields like I showed in my previous answer, since those parsers usually go for property names as fields and I guess you don't want to create classes dynamically during runtime.
I also don't think that it is possible for you to create a dynamic depth of your parent-child-child-child...-relationship with Lists, Arrays or Dictionaries, because those structures have a set depth as soon as they are declared.
Class:
public class MyJsonObject
{
public List<string> Columns = new List<string>();
public string ChildName;
public List<MyJsonObject> Children = new List<MyJsonObject>();
}
Parser:
class JsonParser
{
public static string Parse(MyJsonObject jsonObject)
{
string parse = "{";
parse += string.Join(",", jsonObject.Columns.Select(column => $"\"{column}\": \"\""));
if (!string.IsNullOrEmpty(jsonObject.ChildName))
{
parse += $",\"{jsonObject.ChildName}\":";
parse += $"[{string.Join(",", jsonObject.Children.Select(Parse))}]";
}
parse += "}";
return parse;
}
}
Usage:
class Program
{
static void Main(string[] args)
{
MyJsonObject company = new MyJsonObject();
company.ChildName = "Department";
company.Columns.Add("Id");
company.Columns.Add("Name");
company.Columns.Add("Location");
MyJsonObject department = new MyJsonObject();
department.ChildName = "Employee";
department.Columns.Add("Id");
department.Columns.Add("Name");
department.Columns.Add("CompanyId");
MyJsonObject employee1 = new MyJsonObject();
employee1.Columns.Add("Id");
employee1.Columns.Add("Name");
employee1.Columns.Add("DepartmentId");
MyJsonObject employee2 = new MyJsonObject();
employee2.Columns.Add("Id");
employee2.Columns.Add("Name");
employee2.Columns.Add("DepartmentId");
company.Children.Add(department);
department.Children.Add(employee1);
department.Children.Add(employee2);
var json = JsonParser.Parse(company);
}
}
Output and Link to JSON-Validator:
https://jsonformatter.curiousconcept.com/
{
"Id":"",
"Name":"",
"Location":"",
"Department":[
{
"Id":"",
"Name":"",
"CompanyId":"",
"Employee":[
{
"Id":"",
"Name":"",
"DepartmentId":""
},
{
"Id":"",
"Name":"",
"DepartmentId":""
}
]
}
]
}
Perhaps I'm missing something. If you create the classes you need in the heirachy, instantiate them with data and then serialize them, the structure will be created for you.
using System.Web.Script.Serialization;
public class Employee
{
public int Id {get; set; }
public string Name {get; set; }
public int DepartmentId {get; set; }
}
public class Department
{
public int Id {get; set; }
public string Name {get; set; }
public string CompanyId {get; set; }
public List<Employee> {get; set;}
}
public class Company {
public int Id {get; set; }
public string Name {get; set; }
public string Location {get; set; }
public List<Department> {get; set;}
}
var myCompany = new Company();
// add departments and employees
var json = new JavaScriptSerializer().Serialize(myCompany);
You can use dynamic:
//here your database
dynamic[] company = new object[] { new { Name = "Company1", DepartmentId = 1 }, new { Name = "Company2", DepartmentId = 2 } };
dynamic[] department = new object[] { new { DepartmentId = 1, Name = "Department1" }, new { DepartmentId = 2, Name = "Department2" } };
//select from database
var data = from c in company
join d in department on c.DepartmentId equals d.DepartmentId
select new {Name = c.Name, Department = d};
var serialized = JsonConvert.SerializeObject(data);
result:
[
{
"Name": "Company1",
"Department": {
"DepartmentId": 1,
"Name": "Department1"
}
},
{
"Name": "Company2",
"Department": {
"DepartmentId": 2,
"Name": "Department2"
}
}
]
Ok, lets try like this. First of all as i understand your preblem: u have arrays of properties of parents and child and u neet to convert it to json object.
The point is here:
public static ExpandoObject DicTobj(Dictionary<string, object> properties)
{
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)eo;
foreach (var childColumn in properties)
eoColl.Add(childColumn);
return eo;
}
U use dynamic and ExpandoObject to convert dictionary to object
The other code is trivial: u put all your objects to one using dynamic type
and serialize it.
The full code:
public static Child Child1 { get; set; } = new Child
{
Name = "Child1"
};
public static Parent Parent1 { get; set; } = new Parent
{
Name = "Parent1"
};
public static Parent Parent2 { get; set; } = new Parent
{
Name = "Parent2"
};
private static void Main(string[] args)
{
var result = GetData(Child1, new List<Parent> {Parent1, Parent2});
Console.WriteLine(result);
}
/// <summary>
/// This is the magic: convert dictionary of properties to object with preperties
/// </summary>
public static ExpandoObject DicTobj(Dictionary<string, object> properties)
{
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>) eo;
foreach (var childColumn in properties)
eoColl.Add(childColumn);
return eo;
}
public static string GetData(Child model, List<Parent> parents)
{
var childColumns = GetColumns(model);
dynamic child = DicTobj(childColumns);
var parentsList = new List<object>();
foreach (var parent in parents)
{
var parentColumns = GetColumns(parent);
var parentObj = DicTobj(parentColumns);
parentsList.Add(parentObj);
}
child.Parents = parentsList;
return JsonConvert.SerializeObject(child);
}
/// <summary>
/// this is STUB method for example
/// I change return type from string[] to Dictionary[columnName,ColumnValue], becouse u need not only column names, but
/// with it values, i gues. If not, look commented example at the end of this method
/// </summary>
public static Dictionary<string, object> GetColumns(object model)
{
var result = new Dictionary<string, object>();
if (model == Child1)
{
result.Add("Id", "1");
result.Add("Name", "Child1");
result.Add("Location", "SomeLocation");
}
if (model == Parent1)
{
result.Add("Id", "2");
result.Add("Name", "Parent1");
result.Add("SomeProperty1", "SomeValue1");
}
if (model == Parent2)
{
result.Add("Id", "3");
result.Add("Name", "Parent1");
result.Add("SomeProperty3", "SomeValue2");
}
//if u have only columNames and dont need values u can do like this
//var columns = new[] {"Id", "Name", "SomeProperty1"};//this u get from DB
//return columns.ToDictionary(c => c, c => new object());
return result;
}
}
public class Child
{
public string Name { get; set; } // Contains Employee
//Other properties and info related to process sql query and connection string
}
public class Parent
{
public string Name { get; set; } // Contains Company,Department.
public string SqlQuery { get; set; } // query related to Company and Department.
//Other properties and info related to connection string
}
And result output:
{
"Id": "1",
"Name": "Child1",
"Location": "SomeLocation",
"Parents": [
{
"Id": "2",
"Name": "Parent1",
"SomeProperty1": "SomeValue1"
},
{
"Id": "3",
"Name": "Parent1",
"SomeProperty3": "SomeValue2"
}
]
}
You can pass any kind of object even if you don't have a fixed structure:
Newtonsoft.Json.JsonConvert.SerializeObject(new yourCustomObject)
By using this.
The best way to to get this result
- You have to create a new class which has the relation of all the class. Then use the
Newtonsoft.Json.JsonConvert.SerializeObject(new organization )
Let creates a new class named organization . Add the relation which you want to see in Json. Then convert into the JSON using JsonConvert.
Or you can use the following dynamic loop
//here your database<br/>
dynamic[] company = new object[] { new { Name = "Company1", DepartmentId = 1 }, new { Name = "Company2", DepartmentId = 2 } };
dynamic[] department = new object[] { new { DepartmentId = 1, Name = "Department1" }, new { DepartmentId = 2, Name = "Department2" } };
//select from database<br/>
var data = from c in company
join d in department on c.DepartmentId equals d.DepartmentId
select new {Name = c.Name, Department = d};
var serialized = JsonConvert.SerializeObject(data);

How do I get a property from a list when parsing JSON in C# with JSON.NET?

I'm able to parse simple properties using JSON.NET with this C# code:
Code C#
WebClient c = new WebClient();
var data = c.DownloadString("http://localhost/json1.json");
JObject o = JObject.Parse(data);
listBox1.Items.Add(o["name"]);
listBox1.Items.Add(o["email"][0]);
listBox1.Items.Add(o["email"][1]);
listBox1.Items.Add(o["website"]["blog"]);
json1.json
{
"name": "Fname Lname",
"email": [
"email#gmail.com",
"email#hotmail.com"
],
"website":
{
"blog": "example.com"
}
}
json2.json
{
"name": "Fname Lname",
"email": [
"email#gmail.com",
"email#hotmail.com"
],
"website":
{
"blog": "example.com"
},
"faculty":
{
"department": [
{
"name": "department.name",
"location": "department.location"
}
]
}
}
From the second JSON file, I'm not able to get name and location from the department. How do I do that in C#?
name : department.name
location: department.location
yourjsonobject.faculty.department[0].name;
yourjsonobject.faculty.department[0].location;
Here is some jsfiddle to help you with this:
http://jsfiddle.net/sCCrJ/
var r = JSON.parse('{"name": "Fname Lname","email": [ "email#gmail.com", "email#hotmail.com"],"website":{ "blog": "example.com"},"faculty":{ "department": [ { "name": "department.name", "location": "department.location" } ]}}');
alert(r.faculty.department[0].name);
alert(r.faculty.department[0].location);
for (var i = 0; i < r.faculty.department.length; i++) {
alert(r.faculty.department[i].name);
}
Your problem is that department is an array of objects (though it happens to just contain one item here), but you're not accessing it like it is. You can use o["faculty"]["department"][0]["name"] to get your data.
You might want to use classes (here are ones auto-converted with http://json2csharp.com/) to more easily work with your data.
public class Website
{
public string blog { get; set; }
}
public class Department
{
public string name { get; set; }
public string location { get; set; }
}
public class Faculty
{
public List<Department> department { get; set; }
}
public class RootObject
{
public string name { get; set; }
public List<string> email { get; set; }
public Website website { get; set; }
public Faculty faculty { get; set; }
}
Then you can get all of the data (instead of hoping the fixed indexes are right, and that you didn't make a typo in the property names) with this code:
WebClient c = new WebClient();
var data = c.DownloadString("http://localhost/json1.json");
var o = JsonConvert.DeserializeObject<RootObject>(data);
listBox1.Items.Add(o.name);
foreach (var emailAddr in o.email)
listBox1.Items.Add(emailAddr);
listBox1.Items.Add(o.website.blog);
foreach (var dept in o.faculty.department)
{
listBox1.Items.Add(dept.name);
listBox1.Items.Add(dept.location);
}

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