Dynamically handle JSON variable

Hello, I have JSON like this:

simples: {
   EA201SPACC25ANID-126276: {},
   GF867HDKLI25ANID-126309: {},
   RT211YUIAD912IDO-126310: {},
},

The variable name is always different. How can we declare a model for a C # class? BTW, I am using JSON.NET

Thanks in advance

+4
source share
1 answer

If your Json structure will persist the same over time

Since you cannot have such a property as EA201SPACC25ANID-126276, the easiest way:

public class MyCustomModel
{
    [JsonProperty("EA201SPACC25ANID-126276")]
    public string Something_1 { get; set; }

    [JsonProperty("GF867HDKLI25ANID-126309")]
    public string Something_2 { get; set; }

    [JsonProperty("RT211YUIAD912IDO-126310")]
    public string Something_3 { get; set; }
}

Than just deserialize the object:

JsonConver.DeserializeObject<MyCustomModel>(myJsonString);

If your Json properties change over time (other names)

If this is your case, you can choose to either get the dictionary, or link it manually. For basic scenarios, the first option should work fine:

public ActionResult(Dictionary<string, string> model)

. , , :

public class MyCustomBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.RequestContext.HttpContext.Request;
        var dictionary = new Dictionary<string, object>();
        foreach(var item in request.QueryString.Keys.Cast<string>())
        {
            // You might want to cast your data into appropriate types...
            dictionary.Add(item, request.QueryString[item]);
        }
        return dictionary;
    }
}

:

public ActionResult Index([ModelBinder(typeof(MyCustomBinder))] Dictionary<string, object> model)
+2

Source: https://habr.com/ru/post/1532587/


All Articles