5

I have camel case JSON like this:

{
  "name": "John",
  "age": 55
}

I need to deserialize it into ExpandoObject but I would like the properties to be in Pascal Case. So I should be able to do this:

dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json);
Console.WriteLine($"{obj.Name} is {obj.Age}");

Any ideas?

Sandy
  • 1,284
  • 2
  • 14
  • 32
  • this https://stackoverflow.com/questions/42994125/how-to-convert-any-pascal-case-json-object-to-camel-case-json-object might give you a clue. – Amr Elgarhy Jul 06 '18 at 20:13
  • 1
    When I run the code in that accepted answer, it does not convert properties to pascal case. – Sandy Jul 06 '18 at 20:17
  • Why an `expando` object if you _"**need** to"_ ? – EdSF Jul 06 '18 at 20:27
  • My business code uses dynamic properties. So I need to use some form of DynamicObject. ExpandoObject is easier because JSON.NET knows how to serialize it. – Sandy Jul 06 '18 at 20:44

1 Answers1

2

My business code uses dynamic properties. So I need to use some form of DynamicObject.

IMHO - I get this, but at least to me, it doesn't explain the need for casing...

In any case, this was an interesting happy hour exercise...and I think this is janky and probably should never see the light of day :)

var json = "{ \"name\": \"John\",  \"age\": 55, \"fooBoo\": 0}";

JObject obj = JObject.Parse(json);

dynamic foo = new ExpandoObject();
var bar = (IDictionary<string, object>) foo;
foreach (JProperty property in obj.Properties())
{
    var janky = property.Name.Substring(0, 1).ToUpperInvariant() + property.Name.Substring(1);
    bar.Add(janky, property.Value);
}

Console.WriteLine($"{foo.Name} , {foo.Age}, {foo.FooBoo}");

TGIF :)

EdSF
  • 11,753
  • 6
  • 42
  • 83