Home > Mobile >  C# get Json value from a file
C# get Json value from a file

Time:05-19

I have a json file and I want to deserialize it into an object, however, for this I need the value parameter of the method: JsonConvert.DeserializeObject<Parametros>(parameter)

I don't know how to get it, I tried to convert it to JObject but it didn't work, any ideas?

My code so far:

IConfiguration configuration = GetConfigurationFromJson();
JObject json = JObject.Parse(JSON_FILE_PATH);
Parametros parametros = JsonConvert.DeserializeObject<Parametros>(json); //Wrong parameter
{
  "boletinConfig": {
    "nBoletin": "00030000",
    "claveSancion": 502,
    "agente": 660050
  }
}
public class Parametros
    {
        public string nBoletin { get; set; }
        public int claveSancion { get; set; }
        public int agente { get; set; }
        public Parametros(string nBoletin, int claveSancion, int agente)
        {
            this.nBoletin = nBoletin;
            this.claveSancion = claveSancion;
            this.agente = agente;
        }
        public Parametros()
        {

        }
    }

CodePudding user response:

It should be like this.

using Newtonsoft.Json;

string jsonTextFromFile = File.ReadAllText(JSON_FILE_PATH);
var parametrosObject = JsonConvert.DeserializeObject<Parametros>(jsonTextFromFile);

You don't need JObject at all.

CodePudding user response:

var jsonString = File.ReadAllText(**Path to File**);

Parameters result = JsonConvert.DeserializeObject<Parameters>(jsonString);
  • Related