【发布时间】:2022-01-19 20:44:36
【问题描述】:
抱歉我的英语不好。但我需要这个方法(ToObject)的一点帮助
我有这门课
namespace Proyects
{
public class AProductType
{
public DateTime CreationDate { get; set; }
public string Product { get; set; }
}
public class AProduct
{
public AProductType A_ProductType { get; set; }
}
public class AProductPlantType
{
public string SerialNumberProfile { get; set; }
}
public class ToPlant
{
public List<AProductPlantType> A_ProductPlantType { get; set; }
}
public class AProductDescriptionType
{
public string Language { get; set; }
public string Product { get; set; }
public string ProductDescription { get; set; }
}
public class ToDescription
{
public List<AProductDescriptionType> A_ProductDescriptionType { get; set; }
}
public class Root
{
public AProduct A_Product { get; set; }
public ToPlant to_Plant { get; set; }
public ToDescription to_Description { get; set; }
}
}
我目前正在使用 Root 来在其中保存 Jtoken。但我无法保存来自 Root 类的属性数据。
例如:
var object= myJson.ToObject<Root>();
如果我尝试将数据保存在 AProductType 的专有产品上,我无法使用 ToOject 访问那里。我尝试这样的事情
var object= myJson.ToObject<Root>().A_Product.A_ProductType.Product;
而且不工作,对象 var 变为空。我需要一些方法来保存这个复杂对象周围的数据,然后保存在 Root 的属性中。
真的对不起我的英语,谢谢!!!
编辑:Json 文件
{
"A_Product": {
"A_ProductType": {
"CreationDate": "2020-01-17T00:00:00",
"Product": "158"
}
},
"to_Plant": {
"A_ProductPlantType": [
{
"SerialNumberProfile": "E001"
}
]
},
"to_Description": {
"A_ProductDescriptionType": [
{
"Language": "EN",
"Product": "158",
"ProductDescription": "Terminal LaP (nro de serie + equipo)"
},
{
"Language": "ES",
"Product": "158",
"ProductDescription": "Terminal LaP"
}
]
}
}
编辑 2:
private static List<string> retrieveData(JObject ob, List<Root> listaObjetos)
{
List<string> ListaCodigoProducto = new List<string>();
Root objetoRot = new Root();
var A_Product = ob["A_Product"];
if (A_Product.HasValues)
{
var validacion = ob["A_Product"]["A_ProductType"];
if (validacion.Type == JTokenType.Object)
{
var objeto = validacion.ToObject<AProductType>();
ListaCodigoProducto.Add(objeto.Product);
objetoRot.A_Product.A_ProductType.Product = objeto.Product;
listaObjetos.Add(objetoRot);
}
当我尝试保存产品编号时
objetoRot.A_Product.A_ProductType.Product
它显示 NullReference 异常,我无法访问 Root 对象中的属性
【问题讨论】:
-
由于你的英文不是很好,也许你可以post json pls?
-
myJson.ToObject Root()不是有效的 C#。这不会编译。您可以编辑您的问题以显示您正在使用的实际代码吗?另外,您可以发布您正在使用的无法反序列化的 JSON 吗?有了这些信息,我们可以更轻松地帮助您进行调试。 -
完成了伙计们。抱歉,第一次在这里发帖
-
使用提供的 JSON,我无法重现该问题。如果我说
Console.WriteLine(obj.A_Product.A_ProductType.Product);,它会按预期打印158。 -
添加了更多信息
标签: c# json class object json-deserialization