String reading Json format for C #

0
Hello, I have been having several weeks to read the values of string below, I would like to read the value and in the sites it is very confusing in the search because the type json I have starts with {{ e has an object in the middle of the string [{ . I would like to read the field production and media. I'm not finding the correct code.

I have the string below:

{"d":{"media":12.108320606149539,"lote":"","Opcao":[{"__type":"Model","leitura":70,"producao":1579981660130}],"sinal":"Up"}}

grateful for the help.

    
asked by anonymous 27.03.2018 / 01:08

3 answers

2

To get the json {"d":{"media":12.108320606149539,"lote":"","Opcao":[{"__type":"Model","leitura":70,"producao":1579981660130}],"sinal":"Up"}} and turn it into an object you can use the following code:

obs: [] indicates array, you can read more here in this response

class Obj
{
    public D D { get; set; }
}

class D
{
    public string Media { get; set; }
    public string Lote { get; set; }
    public string Sinal { get; set; }
    public List<Opcao> Opcao { get; set; }
}

class Opcao
{
    public string __type { get; set; }
    public string Leitura { get; set; }
    public string Producao { get; set; }
}

Then, if your project does not already have it, download the library Newtonsoft.Json (it is available via nuget )

and make Deserialize of json.

In the example below I saved it in a string

class Program
{
    static void Main(string[] args)
    {            
        string json = @"{'d':{'media':12.108320606149539,'lote':'','Opcao':[{'__type':'Model','leitura':70,'producao':1579981660130}],'sinal':'Up'}}";

        Obj myObj = new Obj();

        myObj = JsonConvert.DeserializeObject<Obj>(json);

        Console.WriteLine(myObj.D.Media);
    }
}

You can see it working at .NET Fiddle

    
27.03.2018 / 03:39
1

You can use dynamic as you already know the structure and what you want to find is much simpler without having to map the entire structure of an object to get only the value of some attributes that you know where they are.

string json = @"{ 'd':{ 'media':12.108320606149539,'lote':'','Opcao':[{'__type':'Model','leitura':70,'producao':1579981660130}],'sinal':'Up'}}";

dynamic objeto = Newtonsoft.Json.Linq.JObject.Parse(json);

//recuperando o valor de media 
var media = objeto.d.media.Value;

//veja que Opcao é um array de objetos, nesse caso pegamos primeira posição
var producao = objeto.d.Opcao[0].producao.Value;
    
27.03.2018 / 17:52
0

Hello, how are you?

Next, get your json and put it on this site: link

It will generate the classes in C #, then you just do the deserialization.

var objetoRetornado = Newtonsoft.Json.Deserialize<classeGerada>(stringJson);
    
27.03.2018 / 20:50