将对象序列化为json作为ClassName.AttributeName

时间:2016-05-24 05:28:23

标签: c# json serialization

我有一个班级

public class Cust
{
    public string Name { get; set; }
    public string CNIC { get; set; }
}

是否可以使用符号 ClassName.AttributeName 来序列化它:" {\"Cust.Name\":\"sara\",\"Cust.CNIC\":\"123456\"}"而不是"{\"Name\":\"sara\",\"CNIC\":\"123456\"}"

2 个答案:

答案 0 :(得分:2)

public class Cust
{
    [JsonProperty("Cust.Name")]
    public string Name { get; set; }
    [JsonProperty("Cust.CNIC")]
    public string CNIC { get; set; }
}

答案 1 :(得分:1)

1- 最快的脏解决方案(除非您想编写自己的序列化方法)是:

public class Cust
{
    [JsonProperty(PropertyName = nameof(Cust) + "." + nameof(Cust.Name))]
    public string Name { get; set; }
    [JsonProperty(PropertyName = nameof(Cust) + "." + nameof(Cust.CNIC))]
    public string CNIC { get; set; }
}

测试:

static void Main(string[] args)
{
    Cust customer = new Cust() { Name = "aa", CNIC = "bb" };
    string jsonResult = JsonConvert.SerializeObject(customer);
}

<强>输出:

  

{&#34; Cust.Name&#34;:&#34; AA&#34;&#34; Cust.CNIC&#34;:&#34; BB&#34;}

2-解决方法,无需重新发明轮子并编写自己的序列化方法:

(不需要在类Properties上使用JsonProperty属性)

我离开了字符串操作优化,你可以这样做。

static void Main(string[] args)
{
    Cust customer = new Cust() { Name = "aa", CNIC = "bb" };
    string jsonResult = JsonConvert.SerializeObject(customer);

    var props = typeof(Cust).GetProperties().ToList();

    foreach(var prop in props)
    {
        string oldPropJosn = String.Format("\"{0}\":", prop.Name);
        string newPropJson = String.Format("\"{0}.{1}\":", nameof(Cust), prop.Name);
        jsonResult = jsonResult.Replace(oldPropJosn, newPropJson);
    }
}

<强>输出:

  

{&#34; Cust.Name&#34;:&#34; AA&#34;&#34; Cust.CNIC&#34;:&#34; BB&#34;}