0

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?

Community
  • 1
  • 1
matt_rule
  • 1,220
  • 1
  • 12
  • 23
  • Are you sure you really want to build a data structure that has dynamic field names dictated/controlled by the data entered by an end-user? Usually a requirement like this comes about when you are forced to consume someone else's JSON but it seems like you are building from scratch. Do yourself a favor and get rid of this code smell. – David Tansey Mar 19 '15 at 20:48
  • Thanks, I'm using the [Riot summoner-v1.4 API](https://developer.riotgames.com/api/methods#!/960) so not much I can do about it surely? – matt_rule Mar 19 '15 at 20:51
  • I understand and you have my sympathy. – David Tansey Mar 19 '15 at 20:52

1 Answers1

0

And as per usual I answered my own question a few minutes later. :(

The issue was this line: dynamic varPlayer = FromJavaScriptSerializer<PlayerList>(jsonString);

I should have replaced PlayerList with dynamic.

matt_rule
  • 1,220
  • 1
  • 12
  • 23