首页 > 解决方案 > 由于字段名称,无法反序列化当前 JSON 数组

问题描述

我有json(简化版)

var json = @"{""$type"": ""some type"",""$values"": [{""type"": ""some type"",""Name"": """",""Id"": ""someValue"",}]}";
public class JsonStorage
{
    [JsonProperty("$type")] public string Type { get; set; }
    [JsonProperty("$values")] public List<JsonTest> Values { get; set; }
}

public class JsonTest
{
    [JsonProperty("Name")] public string Name { get; set; }
    [JsonProperty("Id")] public string Id { get; set; }
}

反序列化时

JsonConvert.DeserializeObject<JsonStorage>(json);

抛出异常

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Program+JsonStorage' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '$values', line 1, position 34.

如果替换 json 字符串$type->type$values->values并为该 json 设置 json 属性,则DeserializeObject可以正常工作。我可以使用这种方式,在反序列化之前替换。但也许有更好的选择。

示例:https ://dotnetfiddle.net/nxZitW

标签: c#json.netjson.net.net-4.5

解决方案


使用http://quicktype.io在粘贴您的 json 时为我创建的类,我在反序列化发布的数据时没有遇到任何问题(尽管它不喜欢结尾的逗号)

namespace WindowsFormsApp3cs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void SomeButton_Click(object sender, EventArgs e)
        {
            var json = @"{""$type"": ""some type"",""$values"": [{""type"": ""some type"",""Name"": """",""Id"": ""someValue"",}]}";
            var rootClassNameHere = RootClassNameHere.FromJson(json);
        }
    }



    public partial class RootClassNameHere
    {
        [JsonProperty("$type")]
        public string Type { get; set; }

        [JsonProperty("$values")]
        public Value[] Values { get; set; }
    }

    public partial class Value
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("Name")]
        public string Name { get; set; }

        [JsonProperty("Id")]
        public string Id { get; set; }
    }

    public partial class RootClassNameHere
    {
        public static RootClassNameHere FromJson(string json) => JsonConvert.DeserializeObject<RootClassNameHere>(json, WindowsFormsApp3cs.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this RootClassNameHere self) => JsonConvert.SerializeObject(self, WindowsFormsApp3cs.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

推荐阅读