Customize JSON Encoding for MATLAB Classes - MATLAB & Simulink (original) (raw)
Main Content
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 calljsonencode
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) - To display the private property
Age
, customizejsonencode
and add it to themethods
block 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 jsonencode signature, 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}'