-2

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 could use `PropertyNameMappingJsonReader` and `JsonExtensions.DeserializeObject(string json, Func nameMapper, JsonSerializerSettings settings = null)` from [this answer](https://stackoverflow.com/a/47539562/3744182) to [Change key name of data loaded through JsonExtensionData](https://stackoverflow.com/q/47529655/3744182) to trim all property names when read: `JsonExtensions.DeserializeObject(json, s => s.Trim(), settings)`. Does that answer your question? – dbc May 23 '22 at 16:52
  • *I am looking for a generic solution which can work for any Object structure* - then does the previously linked `PropertyNameMappingJsonReader` from [Change key name of data loaded through JsonExtensionData](https://stackoverflow.com/q/47529655/3744182) answer your question? The answer remaps property names at the `JsonReader` level so it's completely generic. – dbc May 24 '22 at 17:19

1 Answers1

0

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Serge
  • 40,935
  • 4
  • 18
  • 45