I have problem with json (i never touch json before). My code is basically copy paste of this Read and parse a Json File in C#.
using (StreamReader r = new StreamReader(RandomUtils.launcherPath() @"\users.json"))
{
string json = r.ReadToEnd();
List<Account> items = JsonConvert.DeserializeObject<List<Account>>(json);
}
public class Account
{
public string users;
public string username;
public string type;
public string uuid;
public string sessionToken;
public string accessToken;
}
and my json (block at users)
{
"users": {
"[email protected]": {
"username": "[email protected]", //Just bug here ill fix later
"type": "mojang",
"uuid": "008d8151613d4ef4bf491520f90930c1",
"sessionToken": "token",
"accessToken": "Anothertoken"
}
}
}
CodePudding user response:
I can not see any list in your json, you have to fix classes
data = JsonConvert.DeserializeObject<Data>(json);
classes
public class Data
{
public Dictionary<string,Account> users { get; set; }
}
public class Account
{
public string username { get; set; }
public string type { get; set; }
public string uuid { get; set; }
public string sessionToken { get; set; }
public string accessToken { get; set; }
}
but if you prefer a list , you can use this code
List<Account> listUsers = ((JObject)JObject.Parse(json)["users"]).Properties()
.Select(x => x.Value.ToObject<Account>())
.ToList();
or if you have only one user
Account account = ((JObject)JObject.Parse(json)["users"]).Properties()
.Select(x => x.Value.ToObject<Account>())
.First();
CodePudding user response:
No, due to your structure List your json should be like:
class SomeClass
{
[JsonProperty("users")]
public List<Account> Users {get;set;}
}
//And your call method should have such signature:
var json = r.ReadToEnd();
var cl = JsonConvert.DeserializeObject<SomeClass>(json);
// use your list like:
cl.Users...