简体   繁体   中英

Javascript & Json: Excluding Fields From Serialization and Deserialization

I work in Java with the Gson package to read/write Json from/to Java classes. One of the main features of Gson is the ability to work with User Defined Strategies where it can be defined programatically which fields to include/exclude.

This works great at the server side, but is there something similar for Javascript/client side?

The JSON.stringify() function takes an optional second parameter referred to as the "replacer". It can be a function or an array, and it guides the serialization process as to how values should be included in the JSON string being constructed.

If the argument is a function, it's passed two arguments, a key (property name) and a value . The this value is arranged to be either undefined if the key is part of the "outer" object being stringified, or a reference to the sub-object if a part of the structure beneath the top-level object. The function can return undefined if the key/value should not be included in the result.

If the value is an array, it dictates what properties of the top-level object to include in the result.

Thus:

var obj = {
  a: 1,
  b: {
    c: 2,
    notMe: "super secret"
  },
  d: 3
};

var str = JSON.stringify(obj, function replacer(key, value) {
  if (this && key === "notMe" && this.c === 2)
    return undefined;
  return value;
});

will result in "str" containing the string

{ "a": 1, "b": { "c": 2 }, "d": 3 }

The "notMe" property of the "b" object would be excluded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM