gpt4 book ai didi

c# - 将 JSON 字符串数组转换为 C# 列表对象,为列表中模型的每个字段返回 "null"值

转载 作者:行者123 更新时间:2023-12-02 09:20:51 24 4
gpt4 key购买 nike

我有字符串格式的 JSON 数组列表,并尝试在 C# 模型列表中进行转换。

我正在使用下面的代码行,但它为模型的每个字段返回 null 值。它在“objectList.Count”行中显示正确的计数,但在调试列表数组时,它显示“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 上的所有属性都是私有(private)的。您可以在此处检查类、结构等的默认可见性: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; }
}

关于c# - 将 JSON 字符串数组转换为 C# 列表对象,为列表中模型的每个字段返回 "null"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42718467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com