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

时间:2015-09-18 08:02:41

标签: c# json 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."}

我尝试像上面一样自定义Category属性的set方法但无法解决它。我不能改变Json字符串。无论如何,我可以解决这个问题。

1 个答案:

答案 0 :(得分:1)

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

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