Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

c# - Read JSON from Dynamic URL and need to populate in Dot-net Core MVC Dropdownlist

I have worked on reading 2 Sample Json files and try to populate in dropdownlist with values title,type,description,filename,height,width,price,rating

Json file 1==>

{"title": "Brown eggs",
"type": "dairy",
"description": "Raw organic brown eggs in a basket",
"filename": "0.jpg",
"height": 600,
"width": 400,
"price": 28.1,
"rating": 4}

Json file 2==>

[{
"title": "Brown eggs",
"type": "dairy",
"description": "Raw organic brown eggs in a basket",
"filename": "0.jpg",
"height": 600,
"width": 400,
"price": 28.1,
"rating": 4}]   

`

` First one works fine with my code below but it's not working for the second one. It gives the error - Cannot convert type 'Newtonsoft.Json.Linq.JArray' to 'Newtonsoft.Json.Linq.JObject'

HomeController.CS Code

    public IActionResult Index()
    {
        Dictionary<string, string> ProductCollectiondict1 = new Dictionary<string, string>();
        //dynamic dynObj1 = JsonConvert.DeserializeObject("{a:1,b:2}");
        // dynamic dynObj1 = JsonConvert.DeserializeObject("[{a:1,b:2}]");

        var webClient = new WebClient();
        var jsonUrlProducts = webClient.DownloadString(@"C:UsersNatarajanSsource
eposKC_EC_WebSite_1KC_EC_WebSite_1wwwrootlibJSONJson_F4.json");
        
        dynamic dynObj1 = JsonConvert.DeserializeObject(jsonUrlProducts);
        var jObj1 = (JObject)dynObj1;

        foreach (JToken token in jObj1.Children())
        {
            if (token is JProperty)
            {
                var prop1 = token as JProperty;
                ProductCollectiondict1.Add(prop1.Name, (string)prop1.Value);
            }
        }

        ViewData["selectedProductTextDict1"] = ProductCollectiondict1;
        return View();
    }

Index.cshtml Code

 @Html.DropDownList("ddlProductByText1",
       new SelectList((System.Collections.IEnumerable)ViewData["selectedProductTextDict1"], "Value", "Key"))

Still a long way to go in this task for various dynamic?JSON URLs . Please kindly?help me guide me soon

question from:https://stackoverflow.com/questions/65880420/read-json-from-dynamic-url-and-need-to-populate-in-dot-net-core-mvc-dropdownlist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...