Customize JSON Encoding for MATLAB Classes
This example shows how to customize the jsonencode function for a
user-defined MATLAB® class.
This class Person.m has a public property Name
and a private property Age. If you call
jsonencode to encode the data, the function only converts the
public property.
classdef Person properties Name; end properties (Access = private) Age; end methods function obj = Person(name,age) obj.Name = name; obj.Age = age; end end end
Display a JSON-encoded instance of
Person.obj = Person('Luke',19); jsonencode(obj)ans = '{"Name":"Luke"}'To display the private property
Age, customizejsonencodeand add it to themethodsblock of classPerson:classdef Person properties Name; end properties (Access = private) Age; end methods function obj = Person(name,age) obj.Name = name; obj.Age = age; end end function json = jsonencode(obj, varargin) s = struct("Name", obj.Name, "Age", obj.Age); json = jsonencode(s, varargin{:}); end end
The signature of the function must match the
jsonencodesignature, which takes a class object as input and returns a string or a character vector in JSON format.Display the customized object.
obj = Person('Luke',19); jsonencode(obj)ans = '{"Name":"Luke","Age":19}'