0

According to RFC 7159,

"Hello world!"

is valid JSON.

How can I deserialize such strings to objects?

Imaging something like:

   [DataContract]
   public class StringValueObject {
        public string Value { get; set; }
   }

   StringValueObject result = JsonConvert.DeserializeObject<StringValueObject>("\"Hello world!\"");
Andrey
  • 63
  • 1
  • 6
  • Do you seek [`JsonConvert.ToString()`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_ToString_19.htm)? It *converts the String to its JSON string representation.* – vahdet Mar 14 '19 at 06:35
  • You would just do `JsonConvert.DeserializeObject("\"Hello world!\"");` – dbc Mar 14 '19 at 06:45
  • 1
    Or are you looking for [Json.Net: Serialize/Deserialize property as a value, not as an object](https://stackoverflow.com/q/40480489/3744182)? It's not really clear exactly what your question is. – dbc Mar 14 '19 at 06:47
  • So I have a string in the output and I would like to convert it to the custom object. However, at the moment, I can convert it only to the primitive like string. So I am wondering is it possible to convert it to the object straight away using Newtonsoft.Json? – Andrey Mar 14 '19 at 22:43

1 Answers1

0

Thanks for everyone, I have found it:

    StringValueObject result = JsonConvert.DeserializeObject<StringValueObject>("\"myString\"");

Now working:

    [TypeConverter(typeof(StringValueConverter))]
    public class StringValueObject {
        public string Value { get; set; }
    }

    public class StringValueConverter : TypeConverter {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
            if (sourceType == typeof(string)) {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
            if (destinationType == typeof(StringValueObject)) {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
            if (value is string) {
                return new StringValueObject {Value = (string) value};
            }
            return base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
            if (destinationType == typeof(string) && value is StringValueObject) {
                return ((StringValueObject) value).Value;
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
Andrey
  • 63
  • 1
  • 6