Let's say I have a JSON based string that looks: {"Hello":"1"}
I want to convert it to look like {"HELLO":"1"}
.
I have created an upper case naming strategy:
public class UpperCaseNamingStrategy : NamingStrategy
{
protected override string ResolvePropertyName(string name)
{
return name.ToUpper();
}
}
Which works when manipulating an object:
[Fact]
public void TestUpperCase()
{
var thing = new {Hello = "1"};
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new UpperCaseNamingStrategy { OverrideSpecifiedNames = true }
}
};
var serializeObject = JsonConvert.SerializeObject(thing, jsonSerializerSettings);
Assert.Equal("{\"HELLO\":\"1\"}", serializeObject); // Works fine
}
But when I load in a string via the JObject.Parse
API, it seems to leave the string as is:
[Fact]
public void TestUpperCase2()
{
var thing = JObject.Parse("{\"Hello\":\"1\"}");
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new UpperCaseNamingStrategy { OverrideSpecifiedNames = true }
}
};
var serializeObject = JsonConvert.SerializeObject(thing, jsonSerializerSettings);
Assert.Equal("{\"HELLO\":\"1\"}", serializeObject); // this fails Actual: {"Hello":"1"}
}
In this test I am simulating my use case, I am retrieving a JSON response from a REST API, I am trying to take that response string and convert all of the keys into upper case string.
Doing a little debugging I can see that the object that is getting loaded into the JObject looks something like {{"Hello": "1"}}
.
I just want to point out that the data I am using is much more complex than just simple "hello" I just wanted a quick example, let's say I have 20 fields some being objects some being arrays, is there an easy way I can parse the JSON and have all the keys to use upper case naming.