I have a very undesirable situation which requires me to deserialize the JSON where the values are field names with JSON.NET. Assuming that I have the following JSON which is very properly structured:
{
"name": "tugberk",
"roles": [
{ "id": "1", "name": "admin" },
{ "id": "2", "name": "guest" }
]
}
It's very easy to deserialize this with JSON.NET to a CLR object:
class Program
{
static void Main(string[] args)
{
var camelCaseSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var text = File.ReadAllText("user_normal.txt");
var obj = JsonConvert.DeserializeObject<User>(text, camelCaseSettings);
}
}
public class User
{
public string Name { get; set; }
public Role[] Roles { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
However, in my current case, I have the following horrible JSON which is equivalent to above JSON in terms of values:
{
"name": "tugberk",
"roles": {
"1": { "name": "admin" },
"2": { "name": "guest" }
}
}
As you can see, roles
field is not an array; it's an object which contains other values as objects with it's unique keys as their field names (which is horrible). What's the best way to deserialize this JSON to above User
class with JSON.NET?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…