使用Json.Net转换为对象时出错



我正在接收以下Json字符串作为REST服务的输出:

"CategoryDtls":       
             {
            "category": "S",
            "msgType": "0",
            "sourceId": "21999"
           }

我希望使用Json.net将其转换为c#对象

public partial class CategoryDtls
    {
        private TestChar categoryField;
        public TestChar category
        {
            get
            {
                return categoryField;
            }
            set
            {
                if (value == null)
                {
                    categoryField = null;
                }
                var stringValue = Convert.ToString(value);
                var charClass = new TestChar();
                charClass.SimpleChar = stringValue;
                categoryField = charClass;
            }
        }
        public string msgType { get; set; }
        public string sourceId { get; set; }
    }
public partial class TestChar : object, System.ComponentModel.INotifyPropertyChanged
    {
        private string simpleCharField;
        public string SimpleChar
        {
            get
            {
                return this.simpleCharField;
            }
            set
            {
                this.simpleCharField = value;
                this.RaisePropertyChanged("SimpleChar");
            }
        }
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged(string propertyName)
        {
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null))
            {
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }

当这样做时,我得到一个错误,如

{"Could not cast or convert from System.String to JsonParser.TestChar."}

我尝试像上面那样自定义类别属性的set方法,但无法解决它。我不能改变Json字符串。有没有办法,我可以解决这个问题。

您可以创建一个自定义的CategoryConverter,并通过在您的public TestChar category之上声明它[JsonConverter(typeof(CategoryConverter))]来使用它。

public class CategoryConverter : JsonConverter
{
    // Declared as abstract in JsonConverter so must be overridden
    public override bool CanConvert(Type objectType) { return true; }
    // Declared as abstract in JsonConverter so must be overridden
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return JToken.Load(reader).ToObject<TestChar>();
    }
}

相关内容

  • 没有找到相关文章