using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Globalization;
public static void Main()
var myClass = new MyClass()
Console.WriteLine("{" + string.Join(",", myClass.ToKeyValue().Select(kv => kv.Key + "=" + kv.Value).ToArray()) + "}");
public int Property1 { get; set; }
[System.Text.Json.Serialization.JsonIgnore]
public int Property2 { get; set; }
[Newtonsoft.Json.JsonIgnore]
public int Property3 { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "prop4")]
public int Property4 { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("prop5")]
public int Property5 { get; set; }
public static class ObjectExtensions
public static IDictionary<string, string> ToKeyValue(this object metaToken)
JToken token = metaToken as JToken;
return ToKeyValue(JObject.FromObject(metaToken));
if (token.Annotation<Newtonsoft.Json.JsonIgnoreAttribute>() != null
&& token.Annotation<System.Text.Json.Serialization.JsonIgnoreAttribute>() != null)
Console.WriteLine("jIgnore " + token.Path);
var contentData = new Dictionary<string, string>();
foreach (var child in token.Children().ToList())
var childContent = child.ToKeyValue();
if (childContent != null)
contentData = contentData.Concat(childContent)
.ToDictionary(k => k.Key, v => v.Value);
var jValue = token as JValue;
if (jValue?.Value == null)
var value = jValue?.Type == JTokenType.Date ?
jValue?.ToString("o", CultureInfo.InvariantCulture) :
jValue?.ToString(CultureInfo.InvariantCulture);
Console.WriteLine(token.ToString());
string keyName = token.Path;
var jNameAttr = token.Annotation<System.Text.Json.Serialization.JsonPropertyNameAttribute>();
if (jNameAttr != null && !string.IsNullOrWhiteSpace(jNameAttr.Name))
keyName = jNameAttr.Name;
Console.WriteLine("jName " + keyName);
var jPropertyAttr = token.Annotation<Newtonsoft.Json.JsonPropertyAttribute>();
if (jPropertyAttr != null && !string.IsNullOrWhiteSpace(jPropertyAttr.PropertyName))
keyName = jPropertyAttr.PropertyName;
Console.WriteLine("jProperty " + keyName);
return new Dictionary<string, string> { { keyName, value } };