如何创建可序列化的动态模型?

时间:2013-11-07 09:18:28

标签: c# .net json

我试图创建一个可动态变化的可序列化模型

序列化的JSon将如下所示

{
    "Job" : {
        "LensJobId" : "123546"
        "JobTitle"  : "Manager"
        "PostingDate" : "2013-11-20"
    }
    "Job" : {
        "LensJobId" : "3256987"
        "JobTitle"  : "Supervisor"
        "PostingDate" : "2013-11-20"
    }
}

我目前拥有的可序列化类

Class Job
{
  public string lensjobid {get; set;}
  public string jobtitle{get; set;}
  public string postingdate{get; set;}
}

现在新要求是我必须根据请求ex包括作业内的条目:如果请求lensjobid和jobtitle我必须只包括那些或如果请求询问位置详细信息,如州,国家等那么应该包括在内。

对于上述要求,我提出了如下解决方案

public class DistributionList : List<Distribution>
{

}

[DataContract]
public class Distribution
{   
    [DataMember(Name = "Job")]
    public List<KeyValuePair<string, string>> DistributionValues { get; set; }

}

这个序列化的json输出将是

  [{
            "Job" : [{
                    "Key" : "lensjobid",
                    "Value" : "124353453"
                }, {
                    "Key" : "JobTitle",
                    "Value" : "Manager"
                },
                {
                    "Key" : "PostingDate",
                    "Value" : "2012-13-11"
                }
            ]
        },
{
    "Job" : [{
                    "Key" : "lensjobid",
                    "Value" : "124353453"
                }, {
                    "Key" : "JobTitle",
                    "Value" : "Manager"
                },
                {
                    "Key" : "PostingDate",
                    "Value" : "2012-13-11"
                }
            ]
        }

    ]

但上面看起来很奇怪,有什么方法可以让我看起来像我以前的方法的输出?

谢谢和问候!!

1 个答案:

答案 0 :(得分:0)

使用json.net并创建合约解析程序

public class CustomContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    private IEnumerable<string> propertyNames;

    public CustomContractResolver(IEnumerable<string> propertyNames)
    {
        this.propertyNames = propertyNames;
    }
    protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);
        return properties.Where(p => propertyNames.Contains(p.PropertyName)).ToList();
    }
}

像这样序列化

var jobs = getJobs();    
var contractResolver = new CustomContractResolver(new[]{ "Property1", "Property2" });

string json = Newtonsoft.Json.JsonConvert.SerializeObject(jobs, Newtonsoft.Json.Formatting.Indented,
    new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = contractResolver });