0

In order to reuse an existing code that uses Newtonsoft Json.NET I need to be able to deserialize the whole json content of a stream into a single property of a "BadData" object.

Example:

public class BadDataEntity
{
  [Key]
  public int ID { get; set; }

  public string BadData { get; set; }
}

Is there a combination of attributes I can add to this class so when I deserialize any Json it goes completley as a string into the BadData property?

Thanks.

wndproc
  • 241
  • 2
  • 3
  • 3
    So in other words, you don't really want to deserialize the JSON at all. If that's the case, you don't need Json.NET. Just get the contents of the stream as a string and set the property on the object. – Brian Rogers Dec 30 '15 at 23:28
  • I have a code that deserializes messages from a queue into entities and persist the entities. It will be ideal if I could, using configuration only, use the same process to point to the deadletter queue, use a different entity (BadRecords) and persist the full Json without having to write a separate service. – wndproc Dec 31 '15 at 14:06

1 Answers1

0

If for whatever reason you must parse this class using Json.NET (rather than simply reading the stream into a string then manually constructing your class from it), you can create a custom JsonConverter that loads the JSON into a JToken then stores its string value into your BadDataEntity class:

public class BadDataEntityConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(BadDataEntity).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Note that BadData MUST BE VALID JSON, otherwise this won't work.
        var token = JToken.Load(reader);
        var bad = (existingValue as BadDataEntity ?? new BadDataEntity());
        bad.BadData = JsonConvert.SerializeObject(token, Formatting.Indented);
        return bad;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var bad = (BadDataEntity)value;
        if (bad.BadData == null)
            writer.WriteNull();
        else
        {
            var token = JToken.Parse(bad.BadData);
            token.WriteTo(writer, serializer.Converters.ToArray());
        }
    }
}

Note that the string must contain valid JSON.

Then you can attach the converter to your class like so:

[JsonConverter(typeof(BadDataEntityConverter))]
public class BadDataEntity
{
    [Key]
    public int ID { get; set; }

    public string BadData { get; set; }
}

Or put it in the list of converters, as is shown in the documentation and in this question.

dbc
  • 104,963
  • 20
  • 228
  • 340