Specify array elements in Json.NET?

Using Json.NET 10.0.3. Consider the following example:

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

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

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

And then we try to parse it:

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

An analysis of the foregoing failed with the following message:

Newtonsoft.Json.JsonReaderException: Unexpected character during parsing: {. Path 'id', line 1, position 9.

I know that I can pack int into a class and call it "id", but I wonder if this can be done without this extra work. The reason is that it seems to be a limitation in SQL Server 2016 . See question .

-1
source share
1 answer

You can create a custom JsonConverter to translate between 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; } } 

To use the converter, mark the array property with the [JsonConverter] attribute, as shown below. Please note: the type parameter for the converter must match the type of the array element, and the second attribute parameter must be the name of the property that will be used for values ​​in the JSON array.

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

Here is a roundabout demo: https://dotnetfiddle.net/vUQKV1

0
source

All Articles