我有字符串格式的JSON数组的列表,然后尝试在C#模型列表中转换。
我正在使用以下代码行,但其返回 null 为每个模型字段的值。它在" ObjectList.Count.Count"行中显示正确的计数,但是当调试列表阵列时,其显示" null"显示为" null"每个模型字段的值。
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class TestPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ProfileDetailViewModel viewModel = new ProfileDetailViewModel();
viewModel.ProfileDetailModelList = new List<ProfileDetailModel>();
string content = @"[{""AccountNumber"":""1"",""CompressedAddress"":""1, TEST, READING, Postcode"",""MType"":""10"",""BillNotification"":""Y"",""NewBillAlert"":""N"",""AccountType"":""1234568""}]";
List<ProfileDetailModel> objectList = JsonConvert.DeserializeObject<List<ProfileDetailModel>>(content);
if (objectList.Count > 0)
{
viewModel.Success = true;
viewModel.ProfileDetailModelList = objectList;
}
}
}
public class ProfileDetailViewModel
{
public List<ProfileDetailModel> ProfileDetailModelList { get; set; }
public bool Success { get; set; }
}
public class ProfileDetailModel
{
string AccountNumber { get; set; }
string CompressedAddress { get; set; }
string MType { get; set; }
string BillNotification { get; set; }
string NewBillAlert { get; set; }
string AccountType { get; set; }
}
profiledetailmodel上的所有属性都是私有的。您可以查看clases,structs等的默认可见性...此处:https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
只需添加public
public class ProfileDetailModel
{
public string AccountNumber { get; set; }
public string CompressedAddress { get; set; }
public string MType { get; set; }
public string BillNotification { get; set; }
public string NewBillAlert { get; set; }
public string AccountType { get; set; }
}
您应该将所有属性更改为 public
:
public class ProfileDetailModel
{
public string AccountNumber { get; set; }
public string CompressedAddress { get; set; }
public string MType { get; set; }
public string BillNotification { get; set; }
public string NewBillAlert { get; set; }
public string AccountType { get; set; }
}
将jsonproperty属性添加到所有属性中。请参阅下面的屏幕截图。
public class ProfileDetailModel
{
[JsonProperty]
string AccountNumber { get; set; }
[JsonProperty]
string CompressedAddress { get; set; }
[JsonProperty]
string MType { get; set; }
[JsonProperty]
string BillNotification { get; set; }
[JsonProperty]
string NewBillAlert { get; set; }
[JsonProperty]
string AccountType { get; set; }
}