Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft.Json serialization returns empty json object

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;
    }
}

when I am converting this list to json string by using Newtonsoft.Json it returns array of empty objects.

  string json=JsonConvert.SerializeObject(list);

I am getting following result.

[{},{},{},{},{}]

Please help me regarding this problem.

like image 521
Vivek Mishra Avatar asked Oct 17 '22 06:10

Vivek Mishra


1 Answers

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;

This attribute also allows specifying other options, such as specifying the property name to use when serializing/deserializing:

[JsonProperty("categoryId")]
int Category;
like image 134
JLRishe Avatar answered Oct 18 '22 20:10

JLRishe