How do you modify the Json serialization of just one field using Json.net?

前端 未结 3 1747
無奈伤痛
無奈伤痛 2021-01-21 12:45

Say for example I\'m trying to convert an object with 10 fields to Json, however I need to modify the process of serializing 1 of these fields. At the moment, I\'d have to use m

3条回答
  •  不思量自难忘°
    2021-01-21 12:55

    You might use System.Reflection, however it's slow but you don't have to modify the class

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteStartObject();
    
        Type vType = value.GetType();
        MemberInfo[] properties = vType.GetProperties(BindingFlags.Public
                                            | BindingFlags.Instance);
    
        foreach (PropertyInfo property in properties)
        {
            object serValue = null;
            if (property.Name == "Field4")
            {
                serValue = Convert.ToInt32(property.GetValue(value, null));
            }
            else
            {
                serValue = property.GetValue(value, null);
            }
            writer.WritePropertyName(property.Name);
            serializer.Serialize(writer, serValue);
        }
    
        writer.WriteEndObject();
    }
    

提交回复
热议问题