Is it possible to deserialize a Json string to an object if Json string has member names with leading/trailing white spaces. I am using Newtonsoft.Json as my serialization library.
For example following is my object type:
public class Sample
{
public ComplexType Default {get; set;}
}
public class ComplexType
{
public IEnumerable<string> Data {get; set;}
}
What I want is if I have below Json string then also it should be deserialized to a valid Sample object. Note there are trailing whitespaces in the name below. Decorating "Default" member with [JsonProperty(PropertyName = "Default ")] in the class is not an option because theoretically I can have any number of leading and/or trailing whitespaces.
{
"Default ":
{
"Data":["data1","data2"]
}
}
Please let me know if there is any out of the box support in Newtonsoft.Json or other approach to solve this. I am looking for a generic solution which can work for any Object structure.
UPDATE: Updated object structure and expected solution.
You can't just change JObject property name, it is read only. You can only create a new json object using this code for example
var sampleObj=new JObject();
var jsonParsed=JObject.Parse(json);
foreach (var prop in jsonParsed.Properties())
sampleObj.Add(prop.Name.Trim(),prop.Value);
Sample sample=sampleObj.ToObject<Sample>();
UPDATE
if your object is very complicated , you just have to add the code to iterate children objects. Or maybe it makes some sense to use RegEx for example to fix a json string.