在Json.NET中命名数组元素? [英] Name array elements in Json.NET?

查看:84
本文介绍了在Json.NET中命名数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Json.NET 10.0.3.考虑以下示例:

Using Json.NET 10.0.3. Consider the following sample:

class Foo
{
   [JsonProperty("ids")]
   public int[] MyIds { get; set; }
}

很显然,数组的元素是未命名的.现在考虑以下json:

Obviously, the elements of the array are unnamed. Now consider the following json:

{
  "ids": [{
      "id": 1
    }, {
      "id": 2
    }
  ]
}

然后我们尝试解析它:

var json = @"{""ids"":[{""id"":1},{""id"":2}]}";
var result = JsonConvert.DeserializeObject<Foo>(son);

以上内容的解析失败,并显示以下消息:

Parsing the above fails with the following message:

Newtonsoft.Json.JsonReaderException:遇到意外字符 而解析值:{.路径"ids",第1行,位置9.

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'ids', line 1, position 9.

我知道我可以将int包装在一个类中,并在其中将其命名为"id",但是我想知道如果没有这些额外的工作就可以完成.原因似乎是SQL Server 2016中的限制.参见此问题.

I know I can wrap int in a class and name it "id" there, but I'm wondering if this can be done without this extra work. The reason being what appears to be a limitation in SQL Server 2016. See this question.

推荐答案

您可以创建自定义JsonConverter以便在两种数组格式之间进行转换:

You can make a custom JsonConverter to translate between the two array formats:

class CustomArrayConverter<T> : JsonConverter
{
    string PropertyName { get; set; }

    public CustomArrayConverter(string propertyName)
    {
        PropertyName = propertyName;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray array = new JArray(JArray.Load(reader).Select(jo => jo[PropertyName]));
        return array.ToObject(objectType, serializer);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        IEnumerable<T> items = (IEnumerable<T>)value;
        JArray array = new JArray(
            items.Select(i => new JObject(
                new JProperty(PropertyName, JToken.FromObject(i, serializer)))
            )
        );
        array.WriteTo(writer);
    }

    public override bool CanConvert(Type objectType)
    {
        // CanConvert is not called when the [JsonConverter] attribute is used
        return false;
    }
}

要使用转换器,请使用[JsonConverter]属性标记您的数组属性,如下所示.请注意,转换器的type参数必须与数组的项目类型匹配,并且属性的第二个参数必须是用于JSON数组中的值的属性名称.

To use the converter, mark your array property with a [JsonConverter] attribute as shown below. Note the type parameter for the converter must match the item type of the array, and the second parameter of the attribute must be the property name to use for the values in the JSON array.

class Foo
{
    [JsonProperty("ids")]
    [JsonConverter(typeof(CustomArrayConverter<int>), "id")]
    public int[] MyIds { get; set; }
}

这是一个往返演示: https://dotnetfiddle.net/vUQKV1

这篇关于在Json.NET中命名数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆