Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing through JSON in JSON.NET with unknown property names

I have some JSON Data which looks like this:

{
   "response":{
   "_token":"StringValue",
   "code":"OK",
   "user":{
     "userid":"2630944",
     "firstname":"John",
     "lastname":"Doe",
     "reference":"999999999",
     "guid":"StringValue",
     "domainid":"99999",
     "username":"jdoe",
     "email":"[email protected]",
     "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":"[email protected]"
       },
       "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. 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. 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?

like image 441
claydiffrient Avatar asked Feb 05 '13 18:02

claydiffrient


People also ask

What is JSON parsing exception?

JsonParsingException is used when an incorrect JSON is being parsed.

Should ampersand be escaped in JSON?

Certain characters need to be "escaped" when used as part of JSON, like an ampersand (&). You can manually escape these characters, buta better route is to use the ConvertTo-Json cmdlet. That will output an escaped string of any passed string that can be used as part of a JSON file.

What is JSON parsing example?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is JSONPath parse?

JSONPath is an expression language to parse JSON data. It's very similar to the XPath expression language to parse XML data. The idea is to parse the JSON data and get the value you want.


1 Answers

You can access it via the JToken / JArray / JObject methods. 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"": ""[email protected]"",
                              ""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"": ""[email protected]""
                                },
                                ""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);
        }
    }
}
like image 96
carlosfigueira Avatar answered Oct 21 '22 06:10

carlosfigueira