Skip to content

Instantly share code, notes, and snippets.

@ChuckJonas
Last active June 11, 2020 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChuckJonas/9ace602b4be44a11b0f6ff7f24b20283 to your computer and use it in GitHub Desktop.
Save ChuckJonas/9ace602b4be44a11b0f6ff7f24b20283 to your computer and use it in GitHub Desktop.

Goal

Provide a way to deserailize to a typed apex class, while also accessing any data for keys which were unmapped.

Example:

Apex

class Foo {
   String foo;
   Integer bar;
}

JSON

{
  "foo": "abc",
  "bar": 123,
  "unknownProp": "you didn't know I would be here",
  "from": "from is reserved keyword. Could map this even if you wanted",
}

When calling Foo f = (Foo) JSON.deseralize(jsonStr, Foo.class); the unmapped properties (unknownProp & from) are essentially lost.

You could use JSON.deserializeUntyped as an additional call or with custom mapping logic to solve this problem, but this is either a waste of CPU resources or developer time.

Solutions

A better solution would be to provide the ability to both deseralize to a class AND capture any untyped properties in one call:

1: Provide map to be mutated by JSON.deserialize

Map<String, Object> untypedProps = new Map<String, Object>();
Foo f = (Foo) JSON.deserialize(jsonStr, Foo.class, untypedProps);

2: New method which returns a wrapper object containing both the class and unmapped properties

JSON.DeserializeResult res = JSON.deserializeWithUnmapped(jsonStr, Foo.class); // working title :)
Foo f = (Foo) res.mappedResult;
Map<String, Object> untypedProps = res.unmappedResult;

3: Using attributes to control where unmapped props flow to

class Foo {
   String foo;
   Integer bar;

   @UnMappedJson //working title :)
   Map<String, Object> untypedProps;
}

Foo f = (Foo) JSON.deserialize(jsonStr, Foo.class);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment