根据用户确定要在 Json.Net 中序列化的属性 [英] Determining properties to serialize in Json.Net based on user

查看:14
本文介绍了根据用户确定要在 Json.Net 中序列化的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 ASP MVC Web API.我现在想根据执行请求的用户确定要序列化对象的哪些属性.ApiController 知道用户.基于用户,我有一个函数返回一个字符串数组,其中包含用户在模型上有权使用的属性名称.

I am creating a ASP MVC Web API. I now want to determine what properties to serialize of a object based on the user that is doing the request. The ApiController knows the user. And based on the user I have a function that returns a string array with the property names the user has rights to on the model.

如何将用户传递给 ContractResolver,使其仅影响当前请求,而不影响其他用户的同时请求?

How can I pass the user to the ContractResolver so it only affects the current request and not possible simultanious requests from other users?

推荐答案

您可以创建自定义ContractResolver

var json = JsonConvert.SerializeObject(
                new UserClass() {ID=666, Name="john", SurName="doe"},
                new JsonSerializerSettings() { ContractResolver = new CustomContractResolver(new[]{"ID", "SurName"}) }
            );

在这个例子中,输出的json将只包含IDSurName(不是Name)

in this example, output json will only include ID and SurName (not Name)

public class UserClass
{
    public int ID { set; get; }
    public string Name {set; get;}
    public string SurName { set; get; }
}

public class CustomContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    IEnumerable<string> _allowedProps = null;

    public CustomContractResolver(IEnumerable<string> allowedProps)
    {
        _allowedProps = allowedProps;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return _allowedProps.Select(p=>new JsonProperty() {
            PropertyName = p,
            PropertyType = type.GetProperty(p).PropertyType,
            Readable = true,
            Writable = true,
            ValueProvider = base.CreateMemberValueProvider(type.GetMember(p).First())
        } ).ToList();
    }
}

这篇关于根据用户确定要在 Json.Net 中序列化的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆