1

I am working on a kind of raw converter. When deserializing the decorated attribute, I need to get the raw string from the source.

public class X
{
  [JsonConverter(typeof(MyConverter))]
  public string Y {get;set;}
}

Y will contain a serialized object, let's say {"a":1,"b":2}. Thus from JSON point of view the property Y will contain an object {"Y":{"a":1,"b":2}}. But I need it back as exactly the same string when deserializing.

This approach works, but takes a double load as it is deserialized and serialized back again, and it still can happen that it will be serialized in a different way.

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
  JObject jo = JObject.Load(reader);
  return jo.ToString(serializer.Formatting, serializer.Converters.ToArray());
}

What I need is something that allows me to read as raw string from the beginning till the end of a JSON object. Unfortunately, the JsonReader is a tokenizer, and it does the conversions right ahead while reading.

ZorgoZ
  • 2,974
  • 1
  • 12
  • 34
  • You will have to implement your own `JsonReader` subclass for that, forked from `JsonTextReader`. Things that need preserving: 1) Whitespace formatting; 2) Numeric formatting & prevision (conversion to `double` or `decimal` and back again may tweak precision). `DateTime` recognition can already be disabled by setting [`DateParseHandling = DateParseHandling.None`](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializer_DateParseHandling.htm) so that's not a problem. – dbc Aug 23 '19 at 21:18
  • `JsonReader` does need to tokenize the JSON to verify the JSON is well-formed but possibly a forked `JsonTextReader` could be modified to pipe the characters into some cached `StringWriter` as they are being read? Maybe if you explain your precise requirements we could suggest an easier way? – dbc Aug 23 '19 at 21:18
  • Incidentally if you are mainly concerned with performance, `JRaw.Create(reader).ToString();` may be more performant. See: [Efficiently get full json string in JsonConverter.ReadJson()](https://stackoverflow.com/a/56945050/3744182). – dbc Aug 23 '19 at 21:24
  • @dbc It works, exactly what I needed. Please post it as an answer so that I can accept it. – ZorgoZ Aug 24 '19 at 06:24
  • Well is this a duplicate then, or do you in addition need to set `DateParseHandling.None` to prevent recognition and reformatting of date/time strings? – dbc Aug 24 '19 at 06:31

0 Answers0