Serializing and Deserializing Json objects with C#

Asked

Viewed 6,439 times

3

Consider the JSON below

{
  "atividade_principal": [
    {
      "text": "Atividades de televisão aberta",
      "code": "60.21-7-00"
    }
  ],
  "data_situacao": "03/11/2005",
  "nome": "GLOBO COMUNICACAO E PARTICIPACOES S/A",
  "uf": "RJ",
  "telefone": "(21) 2540-2623",
  "atividades_secundarias": [
    {
      "text": "Reprodução de vídeo em qualquer suporte",
      "code": "18.30-0-02"
    },
    {
      "text": "Portais, provedores de conteúdo e outros serviços de informação na internet",
      "code": "63.19-4-00"
    },
    {
      "text": "Agenciamento de espaços para publicidade, exceto em veículos de comunicação",
      "code": "73.12-2-00"
    },
    {
      "text": "Programadoras",
      "code": "60.22-5-01"
    }
  ],
  "qsa": [
    {
      "qual": "10-Diretor",
      "nome": "CARLOS HENRIQUE SCHRODER"
    },
    {
      "qual": "10-Diretor",
      "nome": "JORGE LUIZ DE BARROS NOBREGA"
    },
    {
      "qual": "10-Diretor",
      "nome": "ROSSANA FONTENELE BERTO"
    },
    {
      "qual": "10-Diretor",
      "nome": "ALI AHAMAD KAMEL ALI HARFOUCHE"
    },
    {
      "qual": "10-Diretor",
      "nome": "WILLY HAAS FILHO"
    },
    {
      "qual": "10-Diretor",
      "nome": "JUAREZ DE QUEIROZ CAMPOS JUNIOR"
    },
    {
      "qual": "10-Diretor",
      "nome": "SERGIO LOURENCO MARQUES"
    },
    {
      "qual": "10-Diretor",
      "nome": "MARCELO LUIS MENDES SOARES DA SILVA"
    },
    {
      "qual": "10-Diretor",
      "nome": "ANTONIO CLAUDIO FERREIRA NETTO"
    },
    {
      "qual": "10-Diretor",
      "nome": "CRISTIANE DELECRODE LOPES SUT RIBEIRO"
    }
  ],
  "situacao": "ATIVA",
  "bairro": "JARDIM BOTANICO",
  "logradouro": "R LOPES QUINTAS",
  "numero": "303",
  "cep": "22.460-901",
  "municipio": "RIO DE JANEIRO",
  "abertura": "31/01/1986",
  "natureza_juridica": "205-4 - Sociedade Anônima Fechada",
  "fantasia": "GCP,TV GLOBO, REDE GLOBO, GLOBO.COM, SOM LIVRE",
  "cnpj": "27.865.757/0001-02",
  "ultima_atualizacao": "2016-11-21T09:10:20.052Z",
  "status": "OK",
  "tipo": "MATRIZ",
  "complemento": "",
  "email": "",
  "efr": "",
  "motivo_situacao": "",
  "situacao_especial": "",
  "data_situacao_especial": "",
  "capital_social": "6408935530.37",
  "extra": {}
}

Classes to be serialized

using System;
using System.Runtime.Serialization;

namespace ITSolution.Web.JSON
{
    [DataContract]
    public class DataContractEmpresa
    {

        [DataMember]
        public string[] atividade_principal { get; set; }

        [DataMember]
        public DateTime data_situacao { get; set; }

        [DataMember]
        public string nome { get; set; }

        [DataMember]
        public string uf { get; set; }

        [DataMember]
        public string telefone { get; set; }

        [DataMember]
        public string[] atividades_secundarias { get; set; }

        [DataMember]
        public string[] qsa { get; set; }

        [DataMember]
        public string situacao { get; set; }

        [DataMember]
        public string bairro { get; set; }

        [DataMember]
        public string logradouro { get; set; }

        [DataMember]
        public string numero { get; set; }

        [DataMember]
        public string cep { get; set; }

        [DataMember]
        public string municipio { get; set; }

        [DataMember]
        public string abertura { get; set; }

        [DataMember]
        public string natureza_juridica { get; set; }

        [DataMember]
        public string fantasia { get; set; }

        [DataMember]
        public string cnpj { get; set; }

        [DataMember]
        public string ultima_atualizacao { get; set; }

        [DataMember]
        public string status { get; set; }

        [DataMember]
        public string tipo { get; set; }

        [DataMember]
        public string complemento { get; set; }

        [DataMember]
        public string email { get; set; }

        [DataMember]
        public string efr { get; set; }

        [DataMember]
        public string motivo_situacao { get; set; }

        [DataMember]
        public string situacao_especial { get; set; }

        [DataMember]
        public string data_situacao_especial { get; set; }

        [DataMember]
        public string capital_social { get; set; }

        [DataMember]
        public string extra { get; set; }

    }
}

Deserializing:

using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ITSolution.Web.JSON
{
    public static class JSONHelper
    {
        public static string GetJSONString(string url)
        {
            HttpWebRequest request =
                (HttpWebRequest)WebRequest.Create(url);
            WebResponse response = request.GetResponse();

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(
                    stream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }

        public static T GetObjectFromJSONString<T>(
            string json) where T : new()
        {
            using (MemoryStream stream = new MemoryStream(
                Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer =
                    new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(stream);
            }
        }

        public static T[] GetArrayFromJSONString<T>(
            string json) where T : new()
        {
            using (MemoryStream stream = new MemoryStream(
                Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer =
                    new DataContractJsonSerializer(typeof(T[]));
                return (T[])serializer.ReadObject(stream);
            }
        }
    }
}

Applying

string url = @"https://www.receitaws.com.br/v1/cnpj/27865757000102";
var json = JSONHelper.GetJSONString(url);    
var r = JSONHelper.GetObjectFromJSONString<DataContractEmpresa>(json);

Exception played

An unhandled Exception of type 'System.Runtime.Serialization.Serializationexception' occurred in System.Runtime.Serialization.dll

Additional information: There was an error deserializing the object of type Itsolution.Web.JSON.DataContractEmpresa. End item expected in namespace'. Text element found in namespace ''.`

The problem is serialization, I’m a beginner and I’ve never touched JSON, as I do to get around this error?

  • If you don’t know how to do a (de)serialization, why not use something as ready as the JSON.NET? I assure you that it is much more complete and easy to use than this helper class there.

  • The problem, I believe, is the collections atividades_secundarias and csa. In JSON are object collections, whereas in c# is an array of strings...

  • What’s in the extra key???

2 answers

5

As stated in the comments, your problem is in the "Mapping of objects". In summary, you need to specify the form that the object will be "deserialized".

Some cases are even complex, and use a tool like the json2csharp helps a lot in this process. It generates the Template according to the json inserted.

But, just change your class so that your code will work:

public class AtividadePrincipal
    {
        public string text { get; set; }
        public string code { get; set; }
    }

    public class AtividadesSecundaria
    {
        public string text { get; set; }
        public string code { get; set; }
    }

    public class Qsa
    {
        public string qual { get; set; }
        public string nome { get; set; }
    }

    public class Extra
    {
    }

    public class DataContractEmpresa
    {
        public List<AtividadePrincipal> atividade_principal { get; set; }
        public string data_situacao { get; set; }
        public string nome { get; set; }
        public string uf { get; set; }
        public string telefone { get; set; }
        public List<AtividadesSecundaria> atividades_secundarias { get; set; }
        public List<Qsa> qsa { get; set; }
        public string situacao { get; set; }
        public string bairro { get; set; }
        public string logradouro { get; set; }
        public string numero { get; set; }
        public string cep { get; set; }
        public string municipio { get; set; }
        public string abertura { get; set; }
        public string natureza_juridica { get; set; }
        public string fantasia { get; set; }
        public string cnpj { get; set; }
        public string ultima_atualizacao { get; set; }
        public string status { get; set; }
        public string tipo { get; set; }
        public string complemento { get; set; }
        public string email { get; set; }
        public string efr { get; set; }
        public string motivo_situacao { get; set; }
        public string situacao_especial { get; set; }
        public string data_situacao_especial { get; set; }
        public string capital_social { get; set; }
        public Extra extra { get; set; }
    }

Otherwise, if you want to use the JSON.Net, just change your line for this after installing the package:

var r = JsonConvert.DeserializeObject<DataContractEmpresa>(json);
  • Thank you so much for the post ! It was very helpful !

  • That website you ran is a hand on the wheel!

  • Hello @Andreyhartung, has another site called quicktype that I find more complete. But, I’m glad to have helped.

5


The @Randrade answer is a better way to solve your problem, I just want to add that if you use the package Json.NET, can rename class fields by placing more suggestive names, with the configuration of the Jsonproperty, example:

public abstract class Modelo
{
    [JsonProperty("text")]
    public string Text { get; set; }

    [JsonProperty("code")]
    public string Code { get; set; }
}

public class Qsa
{
    [JsonProperty("qual")]
    public string Qual { get; set; }

    [JsonProperty("nome")]
    public string Nome { get; set; }
}

public class AtividadePrincipal : Modelo
{
}

public class AtividadesSecundarias : Modelo
{
}  

public class Extra
{    
}

public class Consume
{           
    [JsonProperty("atividade_principal")]
    public List<AtividadePrincipal> AtividadePrincipal { get;set;}

    [JsonProperty("atividades_secundarias")]
    public List<AtividadesSecundarias> AtividadesSecundarias { get; set; }

    [JsonProperty("data_situacao")]
    public string DataSituacao { get; set; }

    [JsonProperty("nome")]
    public string Nome { get; set; }

    [JsonProperty("uf")]
    public string Uf { get; set; }

    [JsonProperty("telefone")]
    public string Telefone { get; set; }

    [JsonProperty("qsa")]
    public List<Qsa> Qsa { get; set; }

    [JsonProperty("situacao")]
    public string Situacao { get; set; }

    [JsonProperty("bairro")]
    public string Bairro { get; set; }

    [JsonProperty("logradouro")]
    public string Logradouro { get; set; }

    [JsonProperty("numero")]
    public string Numero { get; set; }

    [JsonProperty("cep")]
    public string Cep { get; set; }

    [JsonProperty("municipio")]
    public string Municipio { get; set; }

    [JsonProperty("abertura")]
    public string Abertura { get; set; }

    [JsonProperty("naturezaJuridica")]
    public string NaturezaJuridica { get; set; }

    [JsonProperty("fantasia")]
    public string Fantasia { get; set; }

    [JsonProperty("cnpj")]
    public string Cnpj { get; set; }

    [JsonProperty("ultima_atualizacao")]
    public DateTime UltimaAtualizacao { get; set; }

    [JsonProperty("status")]
    public string Status { get; set; }

    [JsonProperty("tipo")]
    public string Tipo { get; set; }

    [JsonProperty("complemento")]
    public string Complemento { get; set; }

    [JsonProperty("email")]
    public string Email { get; set; }

    [JsonProperty("efr")]
    public string Efr { get; set; }

    [JsonProperty("motivo_situacao")]
    public string MotivoSituacao { get; set; }

    [JsonProperty("situacao_especial")]
    public string SituacaoEspecial { get; set; }

    [JsonProperty("data_situacao_especial")]
    public string DataSituacaoEspecial { get; set; }

    [JsonProperty("capital_social")]
    public decimal CapitalSocial { get; set; }

    [JsonProperty("extra")]
    public Extra Extra { get; set; }
}

this is a complete example, but with the intention of complementing by serialization of the name for a certain property of its class.

How to use?

var result = JsonConvert.DeserializeObject<Consume>(json);

server for both processes (Serialize and Deserialize), keeping the name pattern.

Observing: the Extra there is only one class left, there is no way to know what is inside, if you specify in your question to supplement the answer

  • 1

    Already answered my second question. Extremely grateful for your reply. Thank you very much !

Browser other questions tagged

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