0

I called someone web api method that return a list:

"[{"departmentNumber":"1","departmentName":"food"},{"departmentNumber":"2","departmentName":"beverage"},{"departmentNumber":"3","departmentName":"apparel"}]"

My Department class:

public class Department
{
    private int _departmentID;
    private string _departmentName;

    public Department(int DepartmentID, string DepartmentName)
    {
        this._departmentID = DepartmentID;
        this._departmentName = DepartmentName;
    }

    public int DepartmentID
    {
        get { return _departmentID; }
        set { _departmentID = value; }
    }

    public string DepartmentName
    {
        get { return _departmentName; }
        set { _departmentName = value; }
    }
}

The problem is that my when I try to deserialize the json string back into a List, only the DepartmentName data was able to bind but departmentNumber was not because my class have have the property as DepartmentID. How can I know about fixing this without having to change my class?

John Vuong
  • 21
  • 5

2 Answers2

1

Using Json.Net

public class Department {
    [JsonProperty("departmentNumber ")]
    public int DepartmentNumber {get;set;}
    [JsonProperty("departmentName ")]
    public string DepartmentName {get;set;}
}

List<Department> departments = JsonConvert.DeserializeObject<List<Department>>(jsonString);
Zoilo Reyes
  • 573
  • 4
  • 9
0

You can do something like this.

const departments = [{"departmentNumber":"1","departmentName":"food"},{"departmentNumber":"2","departmentName":"beverage"},{"departmentNumber":"3","departmentName":"apparel"}];

departments.forEach(value => {
  console.log(value.departmentName)
  console.log(value.departmentNumber)
})

Kurtz
  • 85
  • 8