You can use dynamic to get the result without error, but it will be slightly troublesome to process. Since you have defined several classes, it is better to use these classes instead of dynamic, just modify some small problems.
- The value of Name and BetOffers may be a type you define, but it may also be a string, so we need an object compatible with these two types, so the Event class is best defined as follows:
{public class Event
public int Id { get; set; }
public object Name { get; set; }
public object BetOffers { get; set; }
} - According to the Json structure, you also need to define an additional class public class Rootobject
{
public Event[] events { get; set; }
}
Then, you can get an object of type RootObject.
If you need to use Name or BetOffer in the subsequent code, you can convert them to Dictionary<TKey,TValue>:var serializer = new JavaScriptSerializer(); Rootobject root = serializer.Deserialize<Rootobject>(json);
If you want to use your defined class instead of Dictionary, you can also convert it like this:foreach (var eventObject in root.Events) { if (eventObject.BetOffers is Dictionary<string,object>) { Dictionary<string, object> bitOffers = (Dictionary<string, object>)eventObject.BetOffers; } if (eventObject.Name is Dictionary<string, string>) { Dictionary<string, string> name = (Dictionary<string, string>)eventObject.Name; } }
Update:public static BetOffer MapDictionaryToBetOffer(Dictionary<string, object> dic) { return new BetOffer { //BetType =dic["BetType"].ToString() BetType = dic["BetType"] == null ? null : dic["BetType"].ToString(), Pick = dic["Pick"].ToString(), Odds = Convert.ToDouble(dic["Odds"]) }; }
Unfortunately, there is no such Attribute in JavaScriptSerializer, we may need to customize one by ourselves.
Please refer to the response in this link:
JavaScriptSerializer - custom property name
In addition, the MapDictionaryToBetOffer method I provided above is flawed. I did not handle the situation when BetType is null. When it is null, the original method will cause NullReferenceException.
Do you have to use JavaScriptSerializer? Is it possible to replace other packages to handle Json? For example, System.Text.Json, you can install it directly in nuget, and then use JsonPropertyNameAttribute to achieve what you need.
If you can change the package, please tell me, the above code will need to be modified a lot.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.