首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建可序列化的动态模型?

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

Stack Overflow用户
提问于 2013-11-07 17:18:28
回答 1查看 98关注 0票数 0

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

序列化后的JSon将如下所示

代码语言:javascript
复制
{
    "Job" : {
        "LensJobId" : "123546"
        "JobTitle"  : "Manager"
        "PostingDate" : "2013-11-20"
    }
    "Job" : {
        "LensJobId" : "3256987"
        "JobTitle"  : "Supervisor"
        "PostingDate" : "2013-11-20"
    }
}

我目前拥有的Serializable类

代码语言:javascript
复制
Class Job
{
  public string lensjobid {get; set;}
  public string jobtitle{get; set;}
  public string postingdate{get; set;}
}

现在的新要求是我必须包括在工作中的条目基于请求例如:如果请求lensjobid和jobtitle我必须包括这些,或者如果请求要求位置详细信息,如州,国家等,那么应该包括在内。

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

代码语言:javascript
复制
public class DistributionList : List<Distribution>
{

}

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

}

的序列化json输出将是

代码语言:javascript
复制
  [{
            "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"
                }
            ]
        }

    ]

但上面的结果对我来说很奇怪,有没有办法让它看起来像我之前方法的输出?

谢谢和问候!!

EN

回答 1

Stack Overflow用户

发布于 2013-11-07 17:35:48

使用json.net并创建协定解析器

代码语言:javascript
复制
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();
    }
}

像这样序列化

代码语言:javascript
复制
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 });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19831977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档