如何通过服务器返回的json数据获取每个客户的Customer id

本文关键字:客户 Customer id json 何通过 服务器 返回 数据获取 | 更新日期: 2023-09-27 18:23:56

我有这样的JSON数据:

[
  {
    "CustomerID": "100",
    "ContactName": "Indocin",
    "City": "David"
  },
  {
    "CustomerID": "200",
    "ContactName": "Enebrel",
    "City": "Sam"
  },
  {
    "CustomerID": "300",
    "ContactName": "Hydralazine",
    "City": "Dhaka"
  }
]

如何通过服务器返回的json数据获取每个客户的客户id?

如何通过服务器返回的json数据获取每个客户的Customer id

您可以执行以下

function func() {
        var JsonData = [
      {
          "CustomerID": "100",
          "ContactName": "Indocin",
          "City": "David"
      },
      {
          "CustomerID": "200",
          "ContactName": "Enebrel",
          "City": "Sam"
      },
      {
          "CustomerID": "300",
          "ContactName": "Hydralazine",
          "City": "Dhaka"
      }
    ];
       GetCustomerID(JsonData);
    }
    function GetCustomerID(JsonData) {
        alert(JsonData);
        var custIDArray = new Array(JsonData.length);
        for (var i = 0; i < JsonData.length; i++) {
            custIDArray[i] = JsonData[i]["CustomerID"];        
        }
        return custIDArray;
    }

我会使用Json.NET库将Json反序列化为对象。您可以通过NuGet安装库。

首先,您需要为JSON创建一个模型:

public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
}

然后,您可以对其进行反序列化,并对所有客户进行迭代以获得信息:

var data = JsonConvert.DeserializeObject<List<Customer>>(json);
foreach (var customer in data)
{
    Console.WriteLine("Customer {0} with ID {1} and City {2}", customer.ContactName, customer.CustomerID, customer.City);
}