Main Content

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
  1. Display a JSON-encoded instance of Person.

    obj = Person('Luke',19);
    jsonencode(obj)
    
    ans =
    
        '{"Name":"Luke"}'
  2. To display the private property Age, customize jsonencode and add it to the methods block of class Person:

    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.

  3. Display the customized object.

    obj = Person('Luke',19);
    jsonencode(obj)
    
    ans =
    
        '{"Name":"Luke","Age":19}'

See Also