Nirav
Nirav

Reputation: 91

Get values from dynamic JSON properties C#

I am working on WCF and I want to get record list array date wise and I need array key as the date which has common in record like below:

{  
   "EventAppGetAllSessionByCustomerIdResult":{  
      "02/22/2017":[  
         {  
            "SessionDate":"02/22/2017"
         }
      ],
      "08/27/2016":[  
         {  
            "SessionDate":"08/27/2016"
         }
      ],
      "Status":{  
         "Description":"Successfull!",
         "Status":1
      }
   }
}

Basically, I want to extract values of SessionDate.

Upvotes: 4

Views: 5019

Answers (2)

kat1330
kat1330

Reputation: 5332

I assumed that you want to extract "SessionDate" property from your JSON. I recommend using JObject.Parse() method.

JObject jObject = JObject.Parse(json);
var result = (JObject)jObject["EventAppGetAllSessionByCustomerIdResult"];

var dates = new List<string>();
foreach(JProperty prop in result.Properties()) 
{
    if (prop.Name != "Status") 
    {
        var values = jObject["EventAppGetAllSessionByCustomerIdResult"][prop.Name].Values<string>("SessionDate");
        dates.AddRange(values);
    }
}

Little explanation:

In your case "02/22/2017" is property which has an array of objects. Each object has "SessionDate" property which holds value. So, following line will extract values from "SessionDate" of all objects:

var values = jObject["EventAppGetAllSessionByCustomerIdResult"][prop.Name].Values<string>("SessionDate");

values represents all dates from a single property. In your case, it can be from "02/22/2017" or from "08/27/2016".

dates will be list of "SessionDate" values. Of course, you have to handle possible exceptions by yourself.

Upvotes: 5

Mohammad
Mohammad

Reputation: 2764

I'm not sure its what you want but try this as your output object:

public class Session
{
    public string SessionDate { get; set; }
}
public class Status
{
    public string Description { get; set; }
    public int Code { get; set; }
}
public class EventAppGetAllSessionByCustomerIdResult
{
    public KeyValuePair<string, Session[]>[] EventAppGetAllSessionByCustomerId { get; set; }

    public Status Status { get; set; }
}

Upvotes: 0

Related Questions