在c#中覆盖Json属性名称

时间:2014-11-12 09:04:11

标签: c# json

我有一个包含以下字段的课程。当需要调用外部rest API方法时,这些属性用于序列化为json对象。

public class Customer
    {
        [JsonProperty(PropertyName = "email")]
        public string Email { get; set; }

        [JsonProperty(PropertyName = "prop[listId]")]
        public string Test{ get; set; }

        // there are lot of properties 
    }

在属性名称Test中,外部API服务调用需要遵循json文件名格式。

prop[7]

在我的情况下,这个7可以根据test,dev和prod等环境进行更改。所以我正在寻找一种方法将listId值移动到app.config中。

我试图按照以下方式执行此操作,但不允许这样做。对于listIdValue,如果指定常量值,它将起作用。

     private string listIdValue = ConfigurationManager.AppSettings["ListIdValue"];

     [JsonProperty(PropertyName = "prop["+listIdValue +"]")]
     public string Test{ get; set; }

2 个答案:

答案 0 :(得分:9)

您必须覆盖DefaultContractResolver并实施自己的机制来提供PropertyName(使用JSON)。我将提供一个完整的示例代码,以显示运行时生成的PropertyName的反序列化和序列化。目前,它会将Test字段修改为Test5(在所有模型中)。您应该实现自己的机制(使用属性,保留名称,表或其他。

class Program
{
    static void Main(string[] args)
    {
        var customer = new Customer() {Email = "asd@asd.com", Test = "asdasd"};
        var a = Serialize(customer, false);
        var b = Serialize(customer, true);
        Console.WriteLine(a);
        Console.WriteLine(b);

        var desA = Deserialize<Customer>(a, false);
        var desB = Deserialize<Customer>(b, true);

        Console.WriteLine("TestA: {0}", desA.Test);
        Console.WriteLine("TestB: {0}", desB.Test);

    }

    static string Serialize(object obj, bool newNames)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        if (newNames)
        {
            settings.ContractResolver = new CustomNamesContractResolver();
        }

        return JsonConvert.SerializeObject(obj, settings);
    }
    static T Deserialize<T>(string text, bool newNames)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        if (newNames)
        {
            settings.ContractResolver = new CustomNamesContractResolver();
        }

        return JsonConvert.DeserializeObject<T>(text, settings);
    }
}
class CustomNamesContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)
    {
        // Let the base class create all the JsonProperties 
        // using the short names
        IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);

        // Now inspect each property and replace the 
        // short name with the real property name
        foreach (JsonProperty prop in list)
        {
            if (prop.UnderlyingName == "Test") //change this to your implementation!
                prop.PropertyName = "Test" + 5;

        }

        return list;
    }
}

public class Customer
{
    [JsonProperty(PropertyName = "email")]
    public string Email { get; set; }

    public string Test { get; set; }

}

输出:

{
  "email": "asd@asd.com",
  "Test": "asdasd"
}
{
  "email": "asd@asd.com",
  "Test5": "asdasd"
}
TestA: asdasd
TestB: asdasd

如您所见,当我们使用Serialize(..., false)时,字段的名称为Test,当我们使用Serialize(..., true)时,字段的名称为Test5,正如所料。这也适用于反序列化。

我已将此答案用作检查我的答案:https://stackoverflow.com/a/20639697/773879

答案 1 :(得分:1)

定义不同的配置模式,如Debug / Release / QA / Staging

然后为每一个添加编译符号。并在您的代码中执行以下操作:

以下我假设你定义了:QA和STAGING

public class Customer
{

    [JsonProperty(PropertyName = "email")]          
    public string Email { get; set; }

    #if QA
        [JsonProperty(PropertyName = "prop[QA_ID]")]
    #elif STAGING
        [JsonProperty(PropertyName = "prop[STAGING_ID]")]
    #endif
    public string Test{ get; set; }

    // there are lot of properties 
}

您也可以将这些配置用于自动部署,这将节省您的时间。