提问者:小点点

如何从json数组字符串中获取键值对[duplicate]


我调用了一个返回列表web api方法:

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

我的部门类别:

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; }
    }
}

问题是,当我尝试将json字符串反序列化为列表时,只有DepartmentName数据能够绑定,而departmentNumber不能绑定,因为我的类具有DepartmentId属性。我怎样才能知道如何在不改变我的类的情况下修复这个问题呢?


共2个答案

匿名用户

使用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);

匿名用户

你可以做这样的事。

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)
})