Manual Configuration of JSON Model

We will set up the JSON model manually on the app, store data on the model and show it on Button click.

The objective is to configure a JSON model with the UI5 App. Then, on a button click the data will be retrieved from the model and displayed in a popup.

We will be following below steps-

  • Create JSON File for JSON Model.
  • Configure the JSON Model on manifest file.
  • Create Button on View to show data.
  • Define Button logic on Controller.

Step 1 - Create JSON File for JSON Model.

Create a JSON File inside model folder and add data to it.

In our case, we created a file named MyModel.json within the model folder and populated it with the following sample data.

model/MyModel.json
{
  "sampleData": "This data is coming from MySampleModel JSON Data"
}

Step 2 - Configure the JSON Model on manifest file.

Define the created JSON file as a JSON model in the manifest.json file under the models section.

In our case, we want to use the JSON model file with the name "MySampleModel", so we define it in the manifest.json file as shown below.

manifest.json
"MySampleModel" : {
    "type": "sap.ui.model.json.JSONModel",
    "uri": "model/MyModel.json"
}

And that is it, our JSON Model has been configured. Now lets try to use it.

Step 3 - Create Button on View.

Create a button in View1.view.xml that, when clicked, reads data from the model and displays it in a popup.

View1.view.xml
<Button id="view1Btn2" text="Show Model Data - SampleData" press="onShowModelData" />

Step 4 - Define Button logic on Controller.

Define the Button event logic on View1.controller.ts to read and display the JSON Model data on popup.

View1.controller.ts
public onShowModelData() : void {
    interface ContentObject {
        sampleData : string
    }

    const myModel = this.getView()?.getModel("MySampleModel") as JSONModel ;
    const modelData = myModel.getData() as ContentObject;

    MessageToast.show(modelData.sampleData);
}

!!!! And its done !!!!