JSON deserialization - Map array indices to properties with JSON.NET

后端 未结 2 1366
北海茫月
北海茫月 2020-11-29 12:33

I want to deserialize a 2-dimensional array to a collection of .net objects. The reason is, array syntax will be easier for my user to work with in an input file. So I just

相关标签:
2条回答
  • 2020-11-29 13:14

    You can do this with a JsonConverter. A simple converter for this purpose would be:

    public class PersonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Person);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            var array = JArray.Load(reader);
            var person = (existingValue as Person ?? new Person());
            person.First = (string)array.ElementAtOrDefault(0);
            person.Last = (string)array.ElementAtOrDefault(1);
            person.Age = (string)array.ElementAtOrDefault(2);
            return person;
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var person = (Person)value;
            serializer.Serialize(writer, new[] { person.First, person.Last, person.Age });
        }
    }
    

    If the specific properties have non-primitive types, you can use JToken.ToObject<T>(JsonSerializer) to deserialize them to the required type:

    person.First = array.ElementAtOrDefault(0)?.ToObject<string>(serializer);
    

    Then you can apply it to your class:

    [JsonConverter(typeof(PersonConverter))]
    public class Person
    {
        public string First { get; set; }
        public string Last { get; set; }
        public string Age { get; set; }
    }
    

    Or use it in settings:

    var settings = new JsonSerializerSettings { Converters = new [] { new PersonConverter() } };
    var list = JsonConvert.DeserializeObject<List<Person>>(json, settings);
    
    0 讨论(0)
  • 2020-11-29 13:14
        public override bool CanConvert(Type objectType)
        {
            if (objectType == typeof(List<Person>)) return true;
    
            return false;
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            List<Person> persons = new List<Person>();
    
            JArray personsArray = (JArray)serializer.Deserialize(reader);
    
            foreach (var personArray in personsArray.Children<JArray>())
            {
                persons.Add(new Person() { 
                             First = personArray[0].Value<string>(),
                             Last = personArray[1].Value<string>(),
                             Age = personArray[2].Value<string>()
                            });
            }
    
            return persons;
        }
    
    0 讨论(0)
提交回复
热议问题