在ASP.NET Web API中是否有@JsonView等效 [英] Is there @JsonView equivalent in ASP.NET Web API

查看:155
本文介绍了在ASP.NET Web API中是否有@JsonView等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring和Java方面有更多的经验,但现在我正在开发ASP.NET Web API项目。

I have much more experience in Spring and Java, but now I am working on ASP.NET Web API project.

所以在Spring中有@JsonView注释我可以为我的DTO注释,所以我可以选择通过REST显示哪些数据。而且我发现它非常有用。但我在ASP.NET中找不到任何等价物。所以我需要为每个特殊用例创建DTO。

So in Spring there is @JsonView annotation with which I can annotate my DTOs, so I could select which data I will show through REST. And I find that very useful. But I cannot find any equivalent in ASP.NET. So I would need to create DTO for every special usecase.

因此,例如在Java中,如果我有UserEntity包含有关用户的信息。有些信息可以公开查看,有些信息只能由管理员查看。 siple解决方案可能是这个

So for example in Java if I have UserEntity that contains information about users. Some information can be seen publicly and some can be seen only by admins. The siple solution could be this

public class UserEntity {
  @JsonView(Views.Public.class)
  @JsonProperty("ID")
  private Integer id;

  @JsonView(Views.Public.class)
  private String name;

  @JsonView(Views.Admin.class)
  @JsonFormat(
  shape = JsonFormat.Shape.STRING, 
  pattern = "dd-MM-yyyy hh:mm:ss")
  private Date dateOfBirth;

  @JsonView(Views.Admin.class)
  private String email;

  @JsonIgnore
  private String password;
  private Integer version;
}

所以在这种情况下,对于ASP.NET中的等效功能,我需要创建2个DTO。一个可以公开看到的用户和一个只能由管理员看到的用户。

So in this case for equivalent functionality in ASP.NET I would need to create 2 DTOs. One for user that can be seen publicly and one for user that can be seen only by admin.

public class PublicUserDto {

  public int ID {get; set;}

  public String Name {get; set;}

}

public class AdminUserDto {

  public int ID {get; set;}

  public String Name {get; set;}

  public DateTime DateOfBirth {get; set;}

  public string Email {get; set;}
}

有没有更好的解决方案?是否有一些机制可以用来在ASP.NET Web API中创建我的数据视图?

Is there any better solution? Is there some mechanism that I can use to create view over my data in ASP.NET Web API?

推荐答案

JSON.NET有名为条件属性初始化的内容。您可以使用以下格式编写方法:

JSON.NET has something called Conditional Property Initialization. You can write a method with the following format:

public bool ShouldSerialize[YourPropertyName]() => someBoolCondition;

JSON.NET将调用该方法来确定是否应该序列化该属性。所以你可以这样:

JSON.NET will call that method to determine if that property should be serialized or not. So you could have something like:

public DateTime DateOfBirth {get; set;}

public bool ShouldSerializeDateOfBirth() => isAdmin;

它不如 JsonView 那么漂亮但是它应该做的工作。

It's not as pretty as JsonView but it should do the job.

这篇关于在ASP.NET Web API中是否有@JsonView等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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