Mirko Fogazzi
Mirko Fogazzi

Reputation: 183

JsonSerializer c# return null struct when try to deserialize an object

Goodmorning,

I have two struct:

    struct SingoloParametroFiltro
    {
        public Variabile variabile { get; set; }
        public string operatore { get; set; }
        public bool non { get; set; }
        public object valore { get; set; }

        public static SingoloParametroFiltro CreaSingoloParametroFiltro(int idVariabile, string Operatore, bool Non, object Valore)
        {
            SingoloParametroFiltro s = new SingoloParametroFiltro();
            s.variabile = Variabile.CreaVariabileDaId(idVariabile);
            s.operatore = Operatore;
            s.non = Non;
            s.valore = Valore;
            return s;
        }
    }

    struct Filtro
    {
        public List<SingoloParametroFiltro> parametroFiltro { get; set; }
        public string nomeFiltro { get; set; }

        public static Filtro CreaFiltro(List<SingoloParametroFiltro> _parFiltro, string _nome)
        {
            Filtro f = new Filtro();
            f.parametroFiltro = _parFiltro;
            f.nomeFiltro = _nome;
            return f;
        }
    }

And the struct of the Variabile:

    struct Variabile
    {
        public int id { get; private set; }
        public string NomeColonna { get;  private set; }
        public string TipoDato { get; private set; }
        public object Val { get; private set; }
        public object Default { get; private set; }
        public int ColonnaAccoppiamento { get; private set; }
        public bool Visibile { get; private set; }
        public bool ChiaveAlbero { get; private set; }
        public int Importanza { get; private set; }
        public bool ChiaveImport { get; private set; }
    }

Now.... I serialize List<SingoloParametroFiltro> and save it on DB. The json string seems ok and all work fine. When i try to Deserialize json string from DB to List<SingoloParametroFiltro> all works great except of Variabile inside SingoloParametroFiltro. The struct Variabile inside SingoloParametroFiltro have all variable set to null or 0.....

Code to Serialize:

JavaScriptSerializer jsSer = new JavaScriptSerializer();
string json = jsSer.Serialize(parametri);

Where parametri is a List<SingoloParametroFiltro>

Code to Deserialize:

JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize<List<SingoloParametroFiltro>>(json);

Anyone can help me?

Upvotes: 1

Views: 2113

Answers (1)

Perfect28
Perfect28

Reputation: 11317

It's because all the setters of the struct Variabile are private.

...
public int id { get; private set; }
public string NomeColonna { get;  private set; }
public string TipoDato { get; private set; }
...

So the deserializer couldn't assign the correct values to the fields. You could try by making it public :

...
public int id { get; set; }
...

Upvotes: 4

Related Questions