CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/59803559/how-to-get-json-property-name-using-reflection-in-c-sharp
public class Employee {
[JsonProperty("emp_id")]
public int Id {get; set;}
[JsonProperty("emp_fname")]
public string Name {get;set;}
[JsonProperty("emp_lname")]
public string LastName {get;set;}
public string SomePropertyWithoutJsonPropertyAdded { get; set; }
}
[JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class SnakeCase {
public int Id {get; set;}
public string Name {get;set;}
public string LastName {get;set;}
[JsonProperty(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public string SomePropertyWithoutJsonPropertyAdded { get; set; }
}
[DataContract]
public class DataContractType {
[DataMember(Name = "emp_id")]
public int Id {get; set;}
[DataMember(Name = "emp_fname")]
public string Name {get;set;}
[DataMember(Name = "emp_lname")]
public string LastName {get;set;}
public string SomePropertyWithoutJsonPropertyAdded { get; set; }
}
public static partial class JsonExtensions
{
static readonly IContractResolver defaultResolver = JsonSerializer.CreateDefault().ContractResolver;
public static object GetJsonProperty<T>(T obj, string jsonName, bool exact = false, IContractResolver resolver = null)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
resolver = resolver ?? defaultResolver;
var contract = resolver.ResolveContract(obj.GetType()) as JsonObjectContract;
if (contract == null)
throw new ArgumentException(string.Format("{0} is not serialized as a JSON object", obj));
var property = contract.Properties.GetProperty(jsonName, exact ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
if (property == null)
throw new ArgumentException(string.Format("Property {0} was not found.", jsonName));
return property.ValueProvider.GetValue(obj); // Maybe check JsonProperty.Readable first, and throw an exception if not?
}
}
public static partial class JsonExtensions
{
public static string [] PropertyNames(Type type)
{
return PropertyNames(defaultResolver, type);
}
//Taken from this answer https://stackoverflow.com/a/45829514/3744182
//To https://stackoverflow.com/questions/33616005/get-a-list-of-json-property-names-from-a-class-to-use-in-a-query-string
public static string [] PropertyNames(this IContractResolver resolver, Type type)
{
if (resolver == null || type == null)
throw new ArgumentNullException();
var contract = resolver.ResolveContract(type) as JsonObjectContract;
if (contract == null)
return new string[0];
return contract.Properties.Where(p => !p.Ignored).Select(p => p.PropertyName).ToArray();
}
}
class TestClass
{
public static void Test()
{
var employee = new Employee
{
Id = 101,
Name = "my name",
LastName = "last name",
SomePropertyWithoutJsonPropertyAdded = "Some Property Without JsonProperty Added",
};
Console.WriteLine("Value of {0} is {1}.", "emp_lname",
JsonExtensions.GetJsonProperty(employee, "emp_lname")); // Prints Value of emp_lname is last name.
Console.WriteLine("Value of {0} is {1}.", "emp_lname",
JsonExtensions.GetJsonProperty(employee, "emp_lname", resolver : new CamelCasePropertyNamesContractResolver()));
Test(employee);
Test(new SnakeCase { Id = 101, Name = "snake case name", LastName = "snake case last name" });
Test(new DataContractType { Id = 101, Name = "data member name", LastName = "data member last name", SomePropertyWithoutJsonPropertyAdded = "foo" });
}
static void Test<T>(T obj)
{
Console.WriteLine("\nTesting all properties of {0}:", obj);
foreach(var name in JsonExtensions.PropertyNames(obj.GetType()))
{
var value = JsonExtensions.GetJsonProperty(obj, name);
Console.WriteLine("Value of {0} is {1}", name, value);
Assert.IsTrue(new JTokenEqualityComparer().Equals(JObject.FromObject(obj)[name], value == null ? JValue.CreateNull() : JToken.FromObject(value)));
}
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
public static string GetNetCoreVersion()
{
//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
//
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
}