使用未知属性名解析JSON.NET中的JSON

时间:2013-02-05 18:11:21

标签: c# json parsing json.net

我有一些JSON数据,如下所示:

{
   "response":{
   "_token":"StringValue",
   "code":"OK",
   "user":{
     "userid":"2630944",
     "firstname":"John",
     "lastname":"Doe",
     "reference":"999999999",
     "guid":"StringValue",
     "domainid":"99999",
     "username":"jdoe",
     "email":"jdoe@jdoe.edu",
     "passwordquestion":"",
     "flags":"0",
     "lastlogindate":"2013-02-05T17:54:06.31Z",
     "creationdate":"2011-04-15T14:40:07.22Z",
     "version":"3753",
     "data":{
       "aliasname":{
         "$value":"John Doe"
       },
       "smsaddress":{
         "$value":"5555555555@messaging.sprintpcs.com"
       },
       "blti":{
         "hideemail":"false",
         "hidefullname":"false"
       },
       "notify":{
         "grades":{
            "$value":"0"
          },
          "messages":{
            "$value":"1"
          }
       },
       "beta_component_courseplanexpress_1":{
         "$value":"true"
       }
    }
  }
}

我正在使用C#和JSON.NET来解析数据。我已经能够使用这种算法成功获取数据:

User MyUser = new User();
JToken data = JObject.Parse(json);
MyUser.FirstName = (string) data.SelectToken("response.user.firstname");
//The same for all the other properties.

问题在于data字段。该字段主要基于用户首选项,并且仅在使用时插入数据。这些字段都是自定义的,开发人员可以无限制地放入任意数量的字段。从本质上讲,它是所有自由格式数据。另外,正如您所注意到的那样,它们可以与数据完全嵌套。

我试图跑:

MyUser.Data = JsonConvert.DeserializeObject<List<JToken>>((string) data.SelectToken("response.user.data");

哪个不起作用。

如何将其转换为在C#对象中使用?

2 个答案:

答案 0 :(得分:12)

如果对您有用,Json.NET实际上可以解析为动态。 这意味着你可以做类似的事情。

dynamic parsedObject = JsonConvert.DeserializeObject("{ test: \"text-value\" }");

parsedObject["test"]; // "text-value"
parsedObject.test; // "text-value"
parsedObject.notHere; // null

编辑:如果你不知道你在寻找什么,可能更适合你迭代这些值。

dynamic parsedObject = JsonConvert.DeserializeObject("{ test: { inner: \"text-value\" } }");
foreach (dynamic entry in parsedObject)
{
    string name = entry.Name; // "test"
    dynamic value = entry.Value; // { inner: "text-value" }
}

答案 1 :(得分:12)

您可以通过JToken / JArray / JObject方法访问它。例如,这将列出数据下的所有键:

public class StackOverflow_14714085
{
    const string JSON = @"{
                          ""response"": {
                            ""_token"": ""StringValue"",
                            ""code"": ""OK"",
                            ""user"": {
                              ""userid"": ""2630944"",
                              ""firstname"": ""John"",
                              ""lastname"": ""Doe"",
                              ""reference"": ""999999999"",
                              ""guid"": ""StringValue"",
                              ""domainid"": ""99999"",
                              ""username"": ""jdoe"",
                              ""email"": ""jdoe@jdoe.edu"",
                              ""passwordquestion"": """",
                              ""flags"": ""0"",
                              ""lastlogindate"": ""2013-02-05T17:54:06.31Z"",
                              ""creationdate"": ""2011-04-15T14:40:07.22Z"",
                              ""version"": ""3753"",
                              ""data"": {
                                ""aliasname"": {
                                  ""$value"": ""John Doe""
                                },
                                ""smsaddress"": {
                                  ""$value"": ""5555555555@messaging.sprintpcs.com""
                                },
                                ""blti"": {
                                  ""hideemail"": ""false"",
                                  ""hidefullname"": ""false""
                                },
                                ""notify"": {
                                  ""grades"": {
                                    ""$value"": ""0""
                                  },
                                  ""messages"": {
                                    ""$value"": ""1""
                                  }
                                },
                                ""beta_component_courseplanexpress_1"": {
                                  ""$value"": ""true""
                                }
                              }
                            }
                          }
                        }";

    public static void Test()
    {
        var jo = JObject.Parse(JSON);
        var data = (JObject)jo["response"]["user"]["data"];
        foreach (var item in data)
        {
            Console.WriteLine("{0}: {1}", item.Key, item.Value);
        }
    }
}