解析仅包含对象值的文本

时间:2019-03-14 06:31:59

标签: json.net json-deserialization

根据RFC 7159,

df1[df1.columns[~df1.columns.str.startswith('C')]].to_csv('A_B.csv', index = False)

是有效的JSON。

如何将此类字符串反序列化为对象?

想象一下:

"Hello world!"

1 个答案:

答案 0 :(得分:0)

感谢大家,我已经找到了:

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

正在工作:

    [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);
        }
    }