How Do I Configure Json.NET Custom Serialization?

后端 未结 3 601
有刺的猬
有刺的猬 2021-01-21 04:47

For reasons beyond my control, I have data coming back from an external service being formatted as an array of array of string: [[\"string_one\", \"string_two\"]]

3条回答
  •  一生所求
    2021-01-21 05:20

    Ended up implementing this using a JsonConverter. I changed MyObject to look like:

    [JsonConverter(typeof(MyObjectConverter))]
    public class MyObject
    {
        public string PropertyOne { get; set; }
        public string PropertyTwo { get; set; }
    }
    

    And then implemented MyObjectConverter:

    public class MyObjectConverter : JsonConverter
    {
        public override object ReadJson (JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            int pos = 0;
            string[] objectIdParts = new string[2];
    
            while (reader.Read())
            {
                if (pos < 1)
                {
                    if (reader.TokenType == JsonToken.String)
                    {
                        objectIdParts[pos] = reader.Value.ToString();
                        pos++;
                    }
                }
                // read until the end of the JsonReader
            }
    
            return new MyObject(objectIdParts);
        }
    
        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException ();
        }
    
        public override bool CanWrite {
            get {
                return base.CanWrite;
            }
        }
    
        public override bool CanRead { get { return true; } }
        public override bool CanConvert (Type objectType) 
        {
            return true;
        }
    }
    

提交回复
热议问题