简体   繁体   English

JSON.Net无法在自定义JsonConverter中反序列化JSON数组

[英]JSON.Net cannot deserialize json array in custom JsonConverter

I've run into a confusing problem that i cannot seem to solve. 我遇到了一个似乎无法解决的令人困惑的问题。

I'm using Json.Net and i've written a custom Json converter to handle a special case in my application. 我正在使用Json.Net,并且编写了一个自定义Json转换器来处理我的应用程序中的特殊情况。 The issue i've run into is in the deserialize or ReadJson method which is throwing an error when it tires to convert a JSON array into an array of strings: 我遇到的问题是在反序列化或ReadJson方法中,当它厌倦了将JSON数组转换为字符串数组时会抛出错误:

在此处输入图片说明

The exact text of the error is: Unexpected token while deserializing object: PropertyName. Path 'RootPages', line 1, position 13. 错误的确切文本是: Unexpected token while deserializing object: PropertyName. Path 'RootPages', line 1, position 13.出现Unexpected token while deserializing object: PropertyName. Path 'RootPages', line 1, position 13. Unexpected token while deserializing object: PropertyName. Path 'RootPages', line 1, position 13.

As you can see from the inspector, the JProperty it is trying to deserialize (RootPages) has been parsed correctly and is valid JSON. 从检查器可以看到,它正尝试反序列化的JProperty(RootPages)已正确解析,并且是有效的JSON。 在此处输入图片说明

So i'm not entirely sure what is going on here, any enlightenment would be greatly appreciated.. 所以我不完全确定这里发生了什么,任何启发都将不胜感激。

If relevant, the original JSON string is as follows: 如果相关,则原始JSON字符串如下:

{
  "RootPages": [
    "TestItem1",
    "TestItem2"
  ],
  "Name": "root"
}

EDIT-CODE: 编辑-CODE:

ReadJson Method: ReadJson方法:

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        if (PartialChildPageSerialization) {
            var jsonObject = JObject.Load(reader);
            var properties = jsonObject.Properties().ToList();

            foreach (var property in objectType.GetProperties()) {
                var type = property.PropertyType;
                object value = null;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ChildPageCollection<>)) {
                    var collection = Activator.CreateInstance(type);
                    var deserializedValue = properties.First(p => p.Name == property.Name).ToObject<string[]>();
                    type.GetMethod("PolulateFromSerializer").Invoke(collection, new object[] {deserializedValue});
                    value = collection;
                }
                else {
                    value = properties.First(p => p.Name == property.Name).ToObject(type);
                }

                property.SetValue(existingValue, value);
            }

            return existingValue;
        }

        return serializer.Deserialize(reader, objectType);
    }

Snippet of the interesting part of ChildPageCollection: ChildPageCollection的有趣部分的代码片段:

public class ChildPageCollection<T> : IList<T> where T : DataPage
{
    public string[] GetNames() => _internalNameList.ToArray();

    internal void PolulateFromSerializer(string[] names) {
        this.Clear();
        _internalNameList.AddRange(names);
        _hasFullList = false;
    }

    private void CheckFullList() {
        if(!_hasFullList)
            throw new InvalidOperationException("Collection has not been fully loaded, and full list is not avialable.");
    }

    private readonly List<T> _internalList = new List<T>();
    private readonly List<string> _internalNameList = new List<string>();
    private bool _hasFullList = true;

    ...
}

I expect this is because the first property is an object with a property called 'RootPages' which is a string[]. 我期望这是因为第一个属性是一个对象,该对象具有名为'RootPages'的属性,该属性为string []。

Unfortunately from the looks of your screenshots you are trying to turn an object into a string array. 不幸的是,从屏幕快照的外观来看,您试图将一个对象转换为字符串数组。

This should work in the example you've given: 这应该在您给出的示例中起作用:

properties.First(p => p.Name == property.Name).Select(o => o.Children().Values<string>()).First().ToArray();

In place of: 代替:

properties.First(p => p.Name == property.Name).ToObject<string[]>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM