您如何使用Json.net修改仅一个字段的Json序列化? [英] How do you modify the Json serialization of just one field using Json.net?

查看:86
本文介绍了您如何使用Json.net修改仅一个字段的Json序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我正在尝试将具有10个字段的对象转换为Json,但是我需要修改序列化其中1个字段的过程.此刻,我将不得不像这样手动写出每个属性:

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 manually write out each property like this:

 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteStartObject();

        writer.WritePropertyName("Field1");
        serializer.Serialize(writer, value.Field1);

        writer.WritePropertyName("Field2");
        serializer.Serialize(writer, value.Field2);

        writer.WritePropertyName("Field3");
        serializer.Serialize(writer, value.Field3);

        writer.WritePropertyName("Field4");
        serializer.Serialize(writer, Convert.ToInt32(value.Field4)); //Modifying one field here

        //Six more times

        writer.WriteEndObject();
    }

这不是好代码,必须编写确实很烦人.有什么方法可以让Json.net自动序列化除一个属性以外的所有属性?还是可能会自动生成一个JObject并对其进行修改?

This isn't good code, and it's really irritating to have to write. Is there any way of getting Json.net to serialize all but one property automatically? Or possibly generate a JObject automatically and modify that?

推荐答案

您可以尝试使用JsonConverterAttribute装饰需要手动修改的属性,并传递适当的JsonConverter类型.

You can try by decorating the property you need to modify manually with JsonConverterAttribute and pass the appropriate JsonConverter type.

例如,使用OP的原始示例:

For example, using OP's original example:

public class IntegerConverter : JsonConverter
{
  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    serializer.Serialize(writer, Convert.ToInt32(value));
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    throw new NotImplementedException();
  }

  public override bool CanConvert(Type objectType)
  {
    return objectType == typeof(string);
  }
}

class TestJson
{
  public string Field1 { get; set; }
  public string Field2 { get; set; }
  public string Field3 { get; set; }

  [JsonConverter(typeof(IntegerConverter))]
  public string Field4 { get; set; }        
}

然后您可以照常使用JsonConvert序列化对象:

You can then serialize the object as usual using JsonConvert:

var test = new TestJson {Field1 = "1", Field2 = "2", Field3 = "3", Field4 = "4"};

var jsonString = JsonConvert.SerializeObject(test);

这篇关于您如何使用Json.net修改仅一个字段的Json序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆