using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public string Street { get; set; }
public string StreetNumber { get; set; }
public static partial class JsonExtensions
public static void Rename(this JToken token, string newName)
throw new ArgumentNullException("token", "Cannot rename a null token");
if (token.Type == JTokenType.Property)
if (token.Parent == null)
throw new InvalidOperationException("Cannot rename a property with no parent");
property = (JProperty)token;
if (token.Parent == null || token.Parent.Type != JTokenType.Property)
throw new InvalidOperationException("This token's parent is not a JProperty; cannot rename");
property = (JProperty)token.Parent;
var existingValue = property.Value;
var newProperty = new JProperty(newName, existingValue);
property.Replace(newProperty);
public static void Test()
Street = "Evergreen Terrace",
var settings = new JsonSerializerSettings
ContractResolver = new CamelCasePropertyNamesContractResolver(),
var jObject = JObject.FromObject(person, JsonSerializer.CreateDefault(settings));
foreach (var item in jObject.Descendants().OfType<JProperty>().Select(p => (Property: p, p.Path)).ToList())
item.Property.Rename("person." + item.Path);
var json = jObject.ToString();
Assert.IsTrue(JToken.DeepEquals(JToken.Parse(GetRequiredJson()), jObject));
static string GetRequiredJson() => @"{
""person.firstName"":""Homer"",
""person.lastName"":""Simpson"",
""person.address.street"":""Evergreen Terrace"",
""person.address.streetNumber"":""742""
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];