Serealize a JSON String C#

Asked

Viewed 113 times

0

I wanted to set up a JSON String, but I can’t create the class the way I need to, I can get information up to the first level, but I can’t create sub-keys.

For example I want the string to be

{
  "nome": "Nome",   
  "familia": {
    "pai": "Nome do PAI",
    "mae": "Nome da MÃE"
   },
  "contato": {
    "celular": "Numero do celular",
    "casa": "Numero da casa"
   }
}

My attempt:

public class Pessoa
    {
        public string nome { get; set; }

        class Familia
        {
            public string pai { get; set; }
            public string mae { get; set; }
        }

        class Contato
        {
            public string celular { get; set; }
            public string casa { get; set; }
        }
        //Essa classe está correta ?
    }

private void btnSerealiza_Click(object sender, EventArgs e)
    {
        Pessoa p = new Pessoa
        {

            nome = "Nome",
            //Como ficaria aqui ?
        };

        tbRetorno.Text = JsonConvert.SerializeObject(p, Formatting.Indented);
    }

I’m new at this so any help or criticism will be welcome.

  • In case you want to know how to fill the Person subobjects at the click of the button?

  • Actually I need to turn the person class into a JSON string, but I wasn’t able to create subchaves

1 answer

3


You need to create separate classes, and within the class Pessoa you will have a class object Familia:

public class Pessoa
{
    public string nome { get; set; }
    public Familia familia {get;set;}
    public Contato contato {get;set;}

}

public class Familia
{
    public string pai { get; set; }
    public string mae { get; set; }
}

public class Contato
{
    public string celular { get; set; }
    public string casa { get; set; }
}

When there are objects within others, we call it aggregation or composition.


Using:

private void btnSerealiza_Click(object sender, EventArgs e)
{
    Pessoa p = new Pessoa
    {
        nome = "Nome",
        familia = new Familia()
        {
            pai = "nome do pai",
            mae = "nome da mae"
        },
        contato = new Contato()
        {
            celular = "123132123",
            casa = "156448"
        }
    };

    tbRetorno.Text = JsonConvert.SerializeObject(p, Formatting.Indented);
}

Recommended reading:

/a/25628/69359

http://www.macoratti.net/11/05/oop_cph1.htm

  • 1

    Thank you very much, it worked perfectly, all the articles I saw gave me an idea but I was not able to do, thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.