questions/42115402/get-json-object-and-parse-it-into-a-c-sharp-object

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

// https://stackoverflow.com/questions/42115402/get-json-object-and-parse-it-into-a-c-sharp-object

namespace Question42115402
{
	public class Person
	{
		public Person ()
		{
	
		}
		public Person (string PK_R_PERSON, string FIRSTNAME, string LASTNAME)
		{
			this.PK_R_PERSON = PK_R_PERSON;
			this.FIRSTNAME = FIRSTNAME;
			this.LASTNAME = LASTNAME;
		}
		public string PK_R_PERSON { get; set; }
		public string FIRSTNAME { get; set; }
		public string LASTNAME { get; set; }
	}
	
	public class TestClass
	{
		static string GetResponse()
		{
			var response = @"[{
    ""PersonsTable"":[
    {""id"":293,""firstname"":""jos"",""lastname"":""don""},
    {""id"":1861,""firstname"":""jef"",""lastname"":""dan""},    
    {""id"":1896,""firstname"":""janine"",""lastname"":""din""}]
}]";
			return response;
		}
		
		public static void Test()
		{
			var response = GetResponse();
			
			Console.WriteLine("Response: ");
			Console.WriteLine(response);
			
			var root = JToken.Parse(response);
			var persons = root
				// Use the JSONPath wildcard operator to select all entries in the "PersonsTable"
				.SelectTokens("[*].PersonsTable[*]")
				// And map the individual entry to a Person type.
				.Select(data => new Person((string)data["id"], (string)data["firstname"], (string)data["lastname"]))
				.ToList();
			
			Console.WriteLine("Result of parsing: ");
			Console.WriteLine(JsonConvert.SerializeObject(persons, Formatting.Indented));
			
		}
	}
						
	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine("");
			
			TestClass.Test();
		}
	}
}
;