Search code examples
sapui5

How to bind nested JSON Data in XML


I want to bind JSON Data to view I have tried as below:

XML:

<m:Select id="Employee" items="{Employee>/EmployeeList}">
<c:Item key="{Employee>key}" text="{Employee>value}" />
<m:layoutData>
    <l:GridData span="L2 M2 S2"/>
</m:layoutData>

This is how my JSON data is :

 var xyz = {
    "Employee": {

        "EmployeeList": [{
                "key": "ram",
                "value": "ram"
            },
            {
                "key": "raj",
                "value": "raj"
            },
            {
                "key": "rani",
                "value": "rani"
            }
        ]
    }
}
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(xyz);
this.getView().setModel(oModel);

I have a select box in view I want to show the employee names as dropdowns in view page.How to bind this XML.Thanks in advance


Solution

  • There are multiple wrong assumptions:

    items="{Employee>/EmployeeList}"
    

    Here you assume that you have a model with the name Employee which has a top-level attribute EmployeeList.

    In fact you have a model with no name and with a top-level attribute Employee.

    You have the choice to:

    • change your binding
    • change your model

    Option A: Change your binding:

    This is your option if you cannot change the model (because it comes from your backend that way).

    Remove the model name from your binding (since your model does not have a name). Build the correct path to your list. At the top of xyz there is a property Employee which is an object that has the property EmployeeList.

    <m:Select id="Employee" items="{/Employee/EmployeeList}">
        <c:Item key="{key}" text="{value}" />
        <m:layoutData>
            <l:GridData span="L2 M2 S2"/>
        </m:layoutData>
    </m:Select>
    

    Option B: Change your model

    If you are not satisfied with your model structure and think that your binding makes sense, you can also alter the model.

    First, change your object so that the EmployeeList is your top level structure:

     var xyz={   
       "EmployeeList":[  
          {  
            "key":"ram",
            "value":"ram"
          },
          {  
            "key":"raj",
            "value":"raj"
          },
          {  
            "key":"rani",
            "value":"rani"
          }
       ]
    }
    

    When setting your model to your view, also provide the name that you expect in the binding:

    this.getView().setModel(oModel, "Employee");