sapui5jsonmodel

What is the difference between setJSON, setData and loadData?


This is regarding the mentioned methods of sap.ui.model.json.JSONModel in SAPUI5:

What is the difference between these 3 methods? When do we use these methods and can we use more than 1 of them for the same purpose?


Solution

  • Have a look at the well documented API Reference for JSONModel.

    In summary (from SAP Documentation):

    setData: Sets the data, passed as a JS object tree, to the model.

    e.g

    var data = {
      "ProductCollection": [{
        "titleId": 0,
        "Name": "Olayinka O",
        "ProductId": "001",
        "chartValue": 75,
        "ProductPicUrl": "sap-icon://competitor"
      }]
    };
    
    
    var oModel = new sap.ui.model.json.JSONModel(data);
    
    //OR 
    var oModel = new sap.ui.model.json.JSONModel(); 
    oModel.setData(data); 
    
    
    /*setdata, could also be a odata url in json format*/

    loadData: Load JSON-encoded data from the server using a GET HTTP request and store the resulting JSON data in the model. Note: Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy, the request can not successfully retrieve data from a different domain, subdomain, or protocol.

    e.g. you can use this to load/GET changes to the data/model and automatically updates the view if that specific model has being binded by reloading the url. If you use load, you don't need the other two in my opinion and loadData with not work on local json data.

    var sURL = "https://cors-anywhere.herokuapp.com/https://services.odata.org/V3/Northwind/Northwind.svc/Products?$format=json";
    var oModel = new sap.ui.model.json.JSONModel();
    
    //if called in setInterval, all changes in the backend will be updated in the view if binded in this case every second
    
    setInterval(oModel.loadData(sURL, true), 1000);

    setJSON : Sets the data, passed as a string in JSON format, to the model.

    i.e. Same as Set Data but strict JSON