1

I am getting a large Json file back from an API that contains some property values that I would like to clean up. A simple example of what I would like to remove is the "<<>>" from the name property.

string json = "{ 'name': '<<>>user name'}";

private class NameFix
{
    [JsonProperty("name")]
    [JsonConverter(typeof(NameFixer))]
    public string Name { get; set; }
}

var name = JsonConvert.DeserializeObject<NameFix>(json);

Is it possible to clean the property during the process of deserialization or should I parse the whole file and modify first? I have looked at custom jsonconverter but I'm not sure if this can accomplish what I need. I tried something like this, but found out the jsonreader is read only so the values cannot be set.

public class NameFixer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, 
JsonSerializer serializer)
    {

    }

    public override object ReadJson(JsonReader reader, Type objectType, 
object existingValue, JsonSerializer serializer)
    {
        if (reader.Value.ToString().Contains("<<>>"))
        {
            reader.Value = "test";
        }
        return serializer.Deserialize(reader, objectType);
    }

    public override bool CanConvert(Type objectType)
    {
        return false;
    }
}
Higgins
  • 11
  • 2
  • 1
    Sounds like you want something like `StringSanitizingConverter` from [this answer](https://stackoverflow.com/a/50009395/3744182) to [Access custom attributes of .NET class inside custom json converter](https://stackoverflow.com/q/49991050/3744182) or `ReplacingStringConverter` from [this answer](https://stackoverflow.com/a/38384977/3744182) to [running a transformation on a Json DeserializeObject for a property](https://stackoverflow.com/q/38351661/3744182). Do those answer your question or do you need something more specific? – dbc Sep 24 '18 at 22:39
  • 1
    The last link had what I needed, turns out I was on the right track. Thanks. – Higgins Sep 24 '18 at 23:14
  • You're welcome. I've gone ahead and marked this as a duplicate of the previous question. – dbc Sep 24 '18 at 23:17

0 Answers0