Json.NET test

CSharp · Console

/Program.cs

using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		// Create Json using coding
		Console.WriteLine("Create Json using coding");
		var json = new JObject {
			{"labresults", JToken.FromObject(Enumerable.Range(1, 10).Select(i =>
				new JObject {
					{"createddate", DateTime.Today.ToString("yyyyMMdd")},
					{"createddatetime", DateTime.Now},
					{"departmentid", i.ToString()},
					{"description", string.Format("Item {0}", i)}
				}))},
			{"totalcount", 10}
		};
		Console.WriteLine(json);
		Console.WriteLine();
		
		// Working with JObject/JArray, Edit and print
		Console.WriteLine("Working with JObject/JArray, Edit and print");
		json["totalcount"] = 9;
		json.Value<JArray>("labresults").Add(new JObject {
			{"createddate", DateTime.Today.ToString("yyyyMMdd")},
			{"createddatetime", DateTime.Now},
			{"departmentid", 11.ToString()},
			{"description", string.Format("Item {0}", 11)}
		});
		json.Value<JArray>("labresults").RemoveAt(0);
		json.Value<JArray>("labresults").RemoveAt(0);
		for (var l = 0; l < json.Value<JArray>("labresults").Count; l++) {
			json["labresults"][l]["departmentid"] = "D" + json["labresults"][l]["departmentid"];
		}
		Console.WriteLine(json);
		Console.WriteLine();
		
		// Linq
		Console.WriteLine("Linq");
		Console.WriteLine(json["labresults"].Cast<JObject>()
						 .Where(obj => obj.Value<string>("departmentid").Contains("3"))
						 .FirstOrDefault());
		Console.WriteLine();
		
		// work with dynamic
		Console.WriteLine("Convert JObject to dynamic");
		dynamic dynamicObj = json;
		
		Console.WriteLine("work with dynamic, Linq");
		Console.WriteLine(string.Join(
			Environment.NewLine, 
			Enumerable.Range(0, (int)dynamicObj.labresults.Count)
			.Select(l => dynamicObj.labresults[l].departmentid)));
		
		Console.WriteLine("work with dynamic, Loop");
		for (var l = 0; l < dynamicObj.labresults.Count; l++) {
			Console.WriteLine(dynamicObj.labresults[l].departmentid);
		}
			
		Console.WriteLine("work with dynamic, Edit");
		dynamicObj.totalcount = 10;
		dynamicObj.labresults.Add(JToken.FromObject(new {
			createddate = DateTime.Today.ToString("yyyyMMdd"),
			createddatetime = DateTime.Now,
			departmentid = "123",
			description = "json 123"
		}));
		Console.WriteLine(json);
		Console.WriteLine();
	}
}
;