0

我正在尝试创建一个可动态更改的可序列化模型

序列化的 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;}
}

现在新的要求是我必须根据请求在工作中包含条目,例如:如果请求要求 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"
                }
            ]
        }

    ]

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

谢谢并恭祝安康!!

4

1 回答 1

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 });
于 2013-11-07T09:35:47.710 回答