Error with creating JSON object.

I am trying to deserialize a JSON file. I created the file myself. I am getting this error when I try to deserialize it. I am able to read the file as normal and output its contents, but when I try to create an object from it, it errors out. There are no "/" in the file. This is my call. It errors out on the second line.
string json = "moves.json"; //Actual filepath is hardcoded
var moves = JsonSerializer.Deserialize<List<Moves>>(json);
string json = "moves.json"; //Actual filepath is hardcoded
var moves = JsonSerializer.Deserialize<List<Moves>>(json);
This is the object class.
using System;
namespace ok
{
public class Moves
{
public string Name { get; set; }
public string Type { get; set; }
public int Attack { get; set; }
public int Accuracy { get; set; }
}
}
using System;
namespace ok
{
public class Moves
{
public string Name { get; set; }
public string Type { get; set; }
public int Attack { get; set; }
public int Accuracy { get; set; }
}
}
This is an example of my JSON.
{
"Moves": [
{
"Name": "Leech Life",
"Type": "BUG",
"Attack": 15,
"Accuracy": 100
},
{
"Name": "Pin Missile",
"Type": "BUG",
"Attack": 15,
"Accuracy": 85
}
]
}
{
"Moves": [
{
"Name": "Leech Life",
"Type": "BUG",
"Attack": 15,
"Accuracy": 100
},
{
"Name": "Pin Missile",
"Type": "BUG",
"Attack": 15,
"Accuracy": 85
}
]
}
3 Replies
ero
ero2y ago
That json is not a List<Move>
MODiX
MODiX2y ago
Ero#1111
REPL Result: Success
using System.Text.Json;

var json = """
{
"Moves": [
{
"Name": "Leech Life",
"Type": "BUG",
"Attack": 15,
"Accuracy": 100
},
{
"Name": "Pin Missile",
"Type": "BUG",
"Attack": 15,
"Accuracy": 85
}
]
}
""";

var root = JsonSerializer.Deserialize<Root>(json);
Console.WriteLine(root);

record Root(
Move[] Moves);

record Move(
string Name,
string Type,
int Attack,
int Accuracy);
using System.Text.Json;

var json = """
{
"Moves": [
{
"Name": "Leech Life",
"Type": "BUG",
"Attack": 15,
"Accuracy": 100
},
{
"Name": "Pin Missile",
"Type": "BUG",
"Attack": 15,
"Accuracy": 85
}
]
}
""";

var root = JsonSerializer.Deserialize<Root>(json);
Console.WriteLine(root);

record Root(
Move[] Moves);

record Move(
string Name,
string Type,
int Attack,
int Accuracy);
Console Output
Root { Moves = Submission#0+Move[] }
Root { Moves = Submission#0+Move[] }
Quoted by
<@!542772576905199626> from #help-0 (click here)
Compile: 725.784ms | Execution: 137.506ms | React with ❌ to remove this embed.
Cvfe Cvt ᵖᵘʳʳ
Oh, I think I understand. So I would need to remove the moves: statement at the beginning to make it into a List? The moves word only occurs at the very beginning. I thought that was needed, but I guess the class itself or moreso the deserializer decides the type. That was it. The error was because I was reading the string name of the filepath. That explains the "/" error. After removing the Moves : and an extra set of brackets, it parsed. Thank you.
Want results from more Discord servers?
Add your server