Newtonsoft.Json序列化返回空的json对象 [英] Newtonsoft.Json serialization returns empty json object
本文介绍了Newtonsoft.Json序列化返回空的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类别的对象的列表:
I have list of objects of following class:
public class Catagory
{
int catagoryId;
string catagoryNameHindi;
string catagoryNameEnglish;
List<Object> subCatagories;
public Catagory(int Id, string NameHindi, string NameEng,List<Object> l)
{
this.catagoryId = Id;
this.catagoryNameHindi = NameHindi;
this.catagoryNameEnglish = NameEng;
this.subCatagories = l;
}
}
public class SubCatagory
{
int subCatagoryId { get; set; }
string subCatNameHindi { get; set; }
string subCatNameEng { get; set; }
public SubCatagory(int Id, string NameHindi, string NameEng)
{
this.subCatagoryId = Id;
this.subCatNameEng = NameEng;
this.subCatNameHindi = NameHindi;
}
}
当我使用Newtonsoft将列表转换为json字符串时,Json返回空对象数组.
when I am converting this list to json string by using Newtonsoft.Json it returns array of empty objects.
string json=JsonConvert.SerializeObject(list);
我得到以下结果.
[{},{},{},{},{}]
[{},{},{},{},{}]
关于这个问题,请帮助我.
Please help me regarding this problem.
推荐答案
默认情况下,NewtonSoft.Json将仅序列化公共成员,因此将您的字段公开:
By default, NewtonSoft.Json will only serialize public members, so make your fields public:
public class Catagory
{
public int catagoryId;
public string catagoryNameHindi;
public string catagoryNameEnglish;
public List<Object> subCatagories;
public Catagory(int Id, string NameHindi, string NameEng, List<Object> l)
{
this.catagoryId = Id;
this.catagoryNameHindi = NameHindi;
this.catagoryNameEnglish = NameEng;
this.subCatagories = l;
}
}
If for some reason you really don't want to make your fields public, you can instead decorate them with the JsonPropertyAttribute to allow them to be serialized and deserialized:
[JsonProperty]
int catagoryId;
这篇关于Newtonsoft.Json序列化返回空的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文