Json.NET: serializing/deserializing arrays

前端 未结 2 1725
小鲜肉
小鲜肉 2021-01-05 17:00

I\'m using a Json.NET library. What\'s the most convenient way of serializing/deserializing arrays in JSON via C#? For example, I\'m trying to deserialize the following text

2条回答
  •  广开言路
    2021-01-05 17:48

    Depends on what you're doing. In your case the easiest way would be to create a JsonConverter. So you could do the following:

    public class IntArrayConverter : JsonCreationConverter
    {
    
        protected override int[] Create(Type objectType, JArray jArray)
        {
            List tags = new List();
    
            foreach (var id in jArray)
            {
                tags.Add(id.Value());
            }
    
            return tags.ToArray();
        }
    }
    
    public abstract class JsonCreationConverter : JsonConverter
    {
        /// 
        /// Create an instance of objectType, based properties in the JSON Array
        /// 
        /// type of object expected
        /// contents of JSON Array that will be deserialized
        /// 
        protected abstract T Create(Type objectType, JArray jObject);
    
        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JArray jArray = JArray.Load(reader);
    
            T target = Create(objectType, jArray);
    
            return target;
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    Then define your model with your new attribute:

    public class Person
    {  
        public string Name { get; set; }
        public string Gender { get; set; }
        [JsonConverter(typeof(IntArrayConverter))]
        public int[] Favorite_numbers { get; set; }
    }
    

    And you can use it as you normally would:

    Person result = JsonConvert.DeserializeObject(@"{
                    ""Name"": ""Christina"",
                    ""Gender"": ""female"",
                    ""Favorite_numbers"": [11, 25 ,23]
                }");
    

提交回复
热议问题