简体   繁体   English

我怎样才能告诉gson Java中将哪些字段添加到json?

[英]How can I tell gson which fields to add to json in Java?

I am using gson to produce json of a collection of objects in Java (Some objects have other collections too). 我正在使用gson在Java中生成对象集合的json(某些对象也具有其他集合)。 This json will be used to populate the web page for users with different clearance levels. 此json将用于为具有不同清除级别的用户填充网页。 Therefore the detail which users can see differs. 因此,用户可以看到的细节有所不同。 Web page only shows what it needs to show however if I use the same json for two different pages then html source code will have more data than it should have. 网页仅显示需要显示的内容,但是,如果我在两个不同的页面上使用相同的json,则html源代码将包含应有的更多数据。 Is there a way to inform gson which variables in which class should be added to the json? 有没有一种方法可以通知gson应该将哪个类中的哪个变量添加到json? As far as I search I could not find an easy way. 据我搜索,我找不到简单的方法。 Either I will produce json myself or clear extra data from the json which gson produced. 我要么自己生成json,要么从gson生成的json中清除额外的数据。

I need to use same classes for different clearance levels and get different json . 我需要对不同的清除级别使用相同的类 ,并获得不同的json

You are trying to use Gson to generate multiple different JSON outputs of the same objects in the same JVM, which is going to be difficult, both in Gson and any good serialization library, because their express goal is essentially the opposite of what you're looking for. 您正在尝试使用Gson在同一个JVM中为同一对象生成多个不同的JSON输出,这在Gson和任何好的序列化库中都将是困难的,因为它们的明确目标实际上与您的目标相反寻找。

The right thing to do would be to instead represent these different clearance levels with different classes, and simply serialize those different classes with Gson as normal. 正确的做法是改为使用不同的类表示这些不同的清除级别,并像正常一样简单地使用Gson序列化这些不同的类。 This way you separate the security model from the serialization, letting you safely pass this information around. 这样,您就可以将安全模型与序列化分开,从而使您可以安全地传递此信息。

/** 
 * Core data class, contains all information the application needs.
 *  Should never be serialized for display to any end user, no matter their level.
 */
public class GlobalData {
  private final String username;
  private final String private_data;
  private final String secure_data;
}

/** Interface for all data display operations */
public interface DisplayData {
  /** Returns a JSON representation of the data to be displayed */
  public String toJson();
}

/**
 * Class for safe display to an untrusted user, only holds onto public
 * data anyone should see.
 */
public class UserDisplayData implements DisplayData {
  private final String username;

  public UserDisplayData(GlobalData gd) {
    username = gd.username;
  }

  public String toJson() {
    return gson.toJson(this);
  }
}

/**
 * Class for safe display to a trusted user, holds private information but
 * does not display secure content (passwords, credit cards, etc.) that even
 * admins should not see.
 */
public class AdminDisplayData implements DisplayData {
  private final String username;
  private final String private_data;

  public AdminDisplayData(GlobalData gd) {
    username = gd.username;
    private_data = gd.private_data;
  }

  public String toJson() {
    // these could be different Gson instances, for instance
    // admin might want to see nulls, while users might not.
    return gson.toJson(this);
  }
}

Now you can sanitize and serialize your data as two separate steps, and use type safety to ensure your GlobalData is never displayed. 现在,您可以按照两个单独的步骤对数据进行清理和序列化,并使用类型安全性确保从未显示您的GlobalData

public void getDisplayData(GlobalData gd, User user) {
  if(user.isAdmin()) {
    return new AdminDisplayData(gd);
  } else {
    return new UserDisplayData(gd);
  }
}

public void showData(DisplayData data) {
  String json = data.toJson();
  // display json however you want
}

If you erroneously tried to call showData(gd) you'd get a clear compilation error that you've done something wrong, and it's a quick fix to get the correct result by calling showData(getDisplayData(gd, user)) which safely and clearly does exactly what you want. 如果您错误地尝试调用showData(gd)则会收到明显的编译错误,说明您做错了什么,这是通过安全地调用showData(getDisplayData(gd, user))获得正确结果的快速解决方案。显然正是您想要的。

you can add a Expose annotations like this on the filed you don't want: 您可以在不需要的文件上添加这样的Expose批注:

@Expose(serialize = false, deserialize = false)
private String address;

some more information here: 一些更多的信息在这里:

https://sites.google.com/site/gson/gson-user-guide#TOC-Gson-s-Expose https://sites.google.com/site/gson/gson-user-guide#TOC-Gson-s-Expose

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Gson仅需的字段映射到Json到Model - How can I mapping Json to Model by Gson only needed fields 如何使用Gson处理具有时间戳的Json响应? java.lang.IndexOutOfBoundsException - How can I handle Json response which have a Timestamp using the Gson ?? java.lang.IndexOutOfBoundsException 如何在JSON中添加属性是由GSON创建的? - How I can add a property to a JSON was created GSON? 如何通过Gson将以下JSON字符串转换为Java Object? - How can I convert the following JSON string to Java Object by Gson? 如何使用gson将选定的字段从JSON映射到Java对象 - How to map selected fields from JSON to Java Object using gson 如何使用GSON将JSON字段转换为JAVA映射 - How to convert JSON fields into a JAVA map using GSON 如何判断哪个字段Gson序列化失败 - How to tell which field failed Gson serialization 如何将JSON反序列化为已知必填字段但可能有多个未知字段的Java类? - How can I deserialize a JSON to a Java class which has known mandatory fields, but can have several unknown fields? 使用 Java Gson,如何将 JSON 格式的字符串转换为 JSON 文件? - Using Java Gson, how can I turn a JSON formatted string into a JSON file? 当JSON使用日期作为属性名称时,如何使用GSON将JSON反序列化为Java Object? - How can I deserialize JSON to Java Object using GSON when the JSON using dates as property names?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM