1

I have to serialize/deserialize a non valid json containing javascript function like

{"Style":{"geometry":myFunction()}}

I m using a custom converter for my property

  [JsonConverter(typeof(PlainJsonStringConverter))]
public string geometry { get; set; } 



public class FunctionSerializer : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(bool));
        }

        public override bool CanRead
        {
            get {
                return true; }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Object result = null;

            //TODO
            return result;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string valueAsString = Convert.ToString(value);

            if (!string.IsNullOrWhiteSpace(valueAsString))
                writer.WriteRawValue(valueAsString);
        }
    }

this work fine on serialization but on deserialization reader try to convert to boolean and throw an exception before calling my converter.

ADyson
  • 57,178
  • 14
  • 51
  • 63
JD11
  • 306
  • 3
  • 11
  • 4
    You're not going to be able to do this with Json.Net. A function is not valid JSON and thus there is no support in the JSON parser for it. Converters are called after the parser has already parsed the input, but the parser fails. – Dark Falcon Oct 31 '18 at 14:00
  • The only option I see for continuing to use Json.Net would be to implement a custom JsonReader, as per https://www.newtonsoft.com/json/help/html/CustomJsonReader.htm – Dark Falcon Oct 31 '18 at 14:09
  • 1
    You can write badly-formed JSON using Json.NET, see [How to deserialize dodgy JSON (with improperly quoted strings, and missing brackets)?](https://stackoverflow.com/q/46788778/344280). But to read not-well-formed JSON you may need to write or subclass `JsonTextReader`. Or maybe not; can you specify the exact syntax of the `myFunction()` string? Will it ever contain whitespace? – dbc Oct 31 '18 at 14:23

1 Answers1

0

Many thanks for all this help.

I use a regexp to add quote before deserializing.

{"fill":{"color":[100,0,46,0.2]},"geometry":function (test) {
 alert('e');
}}

become

{"fill":{"color":[100,0,46,0.2]},"geometry":"function (test) {
 alert('e');
}"}

my code :

jsonTxt = Regex.Replace(jsonTxt, @"(function\s*\(([,a-z]*)?\)\s*)(\{(.*?)?(\{(.*?)(\{(\{(.*?)\})*\})*\})*\})", delegate (Match match)
                        {
                            string v = match.ToString();
                            v = v.Replace("\"", "\\\"");
                            return $"\"{v}\"";
                        }
                        , RegexOptions.Singleline);

For deserializing i always need may converter.

Hope this can help someone

JD11
  • 306
  • 3
  • 11