简体   繁体   English

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

[英]Parsing through JSON in JSON.NET with unknown property names

I have some JSON Data which looks like this: 我有一些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"
       }
    }
  }
}

I am using C# with JSON.NET to parse through the data. 我正在使用C#和JSON.NET来解析数据。 I've been able to sucessfully get data using this algorithm: 我已经能够使用这种算法成功获取数据:

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

The problem is with the data field. 问题出在data字段上。 This field is based on user preferences mostly and data is only inserted as it is used. 该字段主要基于用户首选项,并且仅在使用时插入数据。 The fields are all custom and developers can put in as many as they want without restrictions. 这些字段都是自定义的,开发人员可以无限制地放入任意数量的字段。 Essentially, it's all free form data. 从本质上讲,它是所有自由格式数据。 Also as you notice they can be nested really far with data. 另外正如您所注意到的那样,它们可以与数据嵌套得非常远。

I've tried to run: 我试过跑:

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

which doesn't work. 这不起作用。

How would you go about converting it to be used in a C# object? 您如何将其转换为在C#对象中使用?

Json.NET can actually parse to a dynamic if that is useful to you. 如果对你有用,Json.NET实际上可以解析为动态。 Which means you can do something like. 这意味着你可以做类似的事情。

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

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

Edit: might be more suitable for you to iterate the values if you don't know what you are looking for though. 编辑:如果你不知道你在寻找什么,可能更适合你迭代这些值。

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" }
}

You can access it via the JToken / JArray / JObject methods. 您可以通过JToken / JArray / JObject方法访问它。 For example, this will list all of the keys under the data: 例如,这将列出数据下的所有键:

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM