I am working on a C# web application. The user can specify a set of usernames, in this case "fred" and "george", click a button and the server sends back the following JSON:
{
"fred": {
"id": 4249458,
"name": "fred",
},
"george": {
"id": 3279659,
"name": "george",
}
}
This is then successfully loaded into a string.
The issue is the field names "fred" and "george" are dynamic and there can be any number of them. DataContractJsonSerializer appears to be unable to manage this as it requires field names to be hard-coded in the data contracts.
this thread describes the same problem. The answer there recommends using a JavaScriptSerializer, and using the dynamic
type to represent the "Children" property containing all the dynamically-named fields. The equivalent of "Children" in the JSON I am working with is in fact the top-level object, so I figured I could just load the whole JSON string into a dynamic variable (using kevin's FromJavaScriptSerializer
function defined in the other thread):
public static T FromJavaScriptSerializer<T>(string json)
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
public static string ToStringOutput(object dynamicField)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(dynamicField);
}
dynamic varPlayer = FromJavaScriptSerializer<PlayerList>(jsonString);
Instead this returns an empty object (when printed using ToStringOutput
it is simply "{}").
How do I approach this problem?