I want to create simple game and i need to get values from json or change them. I have 3 classes.
public class Person
{
public string Specjality { get; set; }
public int PWZ { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public List<string> Items { get; set; }
}
public class Monster
{
public string Name { get; set; }
public List<string> Skills { get; set; }
}
public class Root
{
public List<Person> people { get; set; }
public List<Monster> monsters { get; set; }
}
Json file
{
"Person": [
{
"Speciality": "Archer",
"PWZ": 432742,
"Name": "Charlie",
"Surname": "Evans",
"Items": [
"Bow",
"Arrow",
]
},
{
"Speciality": "Soldier",
"PWZ": 432534879,
"Name": "Harry",
"Surname": "Thomas",
"Items": [
"Gun",
"Knife",
]
}
],
"Monster": [
{
"Name": "Papua",
"Skills": [
"Jump",
"SlowWalk",
]
},
{
"Name": "Geot",
"Skills": [
"Run",
"Push",
]
}
]
}
My first problem is how to deserialize it, next how to print chosen values (for examples Skills of first Monster) on the screen and how to change some values (for example change "Jump" from Monster Skills to "Teleport" or change Name of Person). Thanks for all answers.
CodePudding user response:
You're very close. To deserialize update the following:
- Update/fix spelling/typo in
Person
classpublic string Speciality { get; set; }
- Update
Root
property names (the names should match the Json):public class Root { public List<Person> Person { get; set; } public List<Monster> Monster { get; set; } }
- Deserialize to
Root
class:var result = JsonSerializer.Deserialize<Root>(json);
Now, there's also an issue with trailing commas in your Json string. I got this error:
The JSON array contains a trailing comma at the end which is not supported in this mode. Change the reader options.
You can fix the Json string (remove the trailing commas in the arrays), or if you're using System.Text.Json to deserialize you can apply the AllowTrailingCommas
option:
var options = new JsonSerializerOptions { AllowTrailingCommas = true };
var result = JsonSerializer.Deserialize<Root>(json, options);
To display the values:
// iterate over Person/Monster collection
foreach (var person in result.Person)
Console.WriteLine($"Name: {person.Name}, Items: {string.Join(", ", person.Items)}");
foreach (var monster in result.Monster)
Console.WriteLine($"Name: {monster.Name}, Skills: {string.Join(", ", monster.Skills)}");
To modify an item you would just modify the Person
or Monster
instance, then serialize again:
// update name:
result.Person[0].Name = "Alan";
// serialize if you need to:
string json = JsonSerializer.Serialize(result);