Home > front end >  Why is the JSON file not being read?
Why is the JSON file not being read?

Time:10-12

I wrote a class with fields. Then I need an init method to initialize the fields of the class. But it throws an error Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: C. Path '', line 0, position 0.

public class Valera
{
    private int health; 
    private int mana; 
    private int happiness; 
    private int fatigue; 
    private bool dead; 

    public void init()
    {
        var v = JsonConvert.DeserializeObject<Valera>(@"C:\Users\User\RiderProjects\MarginalValera\MarginalValera\Properties\characteristics.json");
        Console.WriteLine(v?.dead);
    }
}

JSON object:

{
  "health" : "100",
  "mana": "50",
  "happiness": "0",
  "fatigue": "50",
  "dead": "false"
}

CodePudding user response:

You need to read the file first then deserialise it:

string rawJson = File.ReadAllText(@"C:\Users\User\RiderProjects\MarginalValera\MarginalValera\Properties\characteristics.json");

Valera obj = JsonConvert.DeserializeObject<Valera>(rawJson);

CodePudding user response:

you have to fix the class, you need public properties with {get; set;}

public class Valera
{
    public int health { get;set; }
    // ... and so on
}

or if for some reason you need the private fields, you will have to create a constructor

public class Valera
{
    private int health;
    private int mana;
    private int happiness;
    private int fatigue;
    private bool dead;

    public Valera(int health,int mana,int happines,int fatique,bool dead){

        this.health = health;
        this.mana = mana;
        this.happiness = happiness;
        this.fatigue =       fatigue;
        this.dead =               dead;
    }
}

also fix the code

string rawJson = File.ReadAllText(@"C:\Users\User\RiderProjects\MarginalValera\MarginalValera\Properties\characteristics.json");

Valera obj = JsonConvert.DeserializeObject<Valera>(rawJson);
  • Related