I have an object of the following class structure:
public class Customer
{
public string ID { get; set; }
public Address contact { get; set; }
}
public class Address
{
public string city { get; set; }
}
and I want the following expected output:
Dictionary<string, string> result = new Dictionary<string, string>()
{
{ "ID", "1" },
{ "contact.city", "Miami" }
};
but I fail because of a nested class structure.
Exception:
Unhandled exception. Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path ‘contact’, line 1, position 21.
at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
My code:
Customer customer = new Customer() { ID = "1", contact = new Address() { city = "Miami" } };
string customerString = Newtonsoft.Json.JsonConvert.SerializeObject(customer);
Dictionary<string, string> result = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(customerString);
Question:
How to achieve this output?
https://dotnetfiddle.net/Q34OxD
1
AFAIK, Newtonsoft.Json does not support (de)serialization for flattened JSON.
You have to implement additional logic to flatten JSON.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
public static class JsonHelper
{
public static Dictionary<string, string> FlattenObject<T>(T source)
where T : class, new()
{
return JObject.FromObject(source)
.Descendants()
.OfType<JValue>()
.ToDictionary(k => k.Path, v => v.Value<string>());
}
}
Caller:
Dictionary<string, string> result = JsonHelper.FlattenObject(JObject.Parse(customerString));
You can provide the customer
instance directly without serialized JSON:
Dictionary<string, string> result = JsonHelper.FlattenObject(customer);
1