0

I have 8 key/value pairs in one JSON URL. I have only 4 matched records in a column. I need to display only 4 matching records in view. I have created One dict model and other list model. ModelList Compare

As per screenshot i need first values from dict like values from list so that i can able to populate json records in view page.

Dict1:


     public void GetList1Void()
        {

            string strAPIUrl = "https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json";
            string jsonUrlProducts;
            using (WebClient client = new WebClient())
            {
                jsonUrlProducts = client.DownloadString(strAPIUrl);
            }
            Dictionary<string, object> Jsondictresults = new Dictionary<string, object>();
            var objResponseB = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jsonUrlProducts);
            foreach (Dictionary<string, object> DictMainKV in objResponseB)
            {
                foreach (KeyValuePair<string, object> item in DictMainKV)
                {
                    Jsondictresults.Add(item.Key, item.Key);
                }
                break;
            }
            ViewBag.VBList1Void = Jsondictresults.Keys;
            ViewData["VdataList1Void"] = Jsondictresults;
        }


List2:

public List<K360mapMaster> GetList2()
{
    List<K360mapMaster> mappingListDb = new List<K360mapMaster>();
    var query = from K360mapMaster in _context.K360mapMasters
                select K360mapMaster;
    var mappings = query.ToList();

    foreach (var mappingData in mappings)
    {
        mappingListDb.Add(new K360mapMaster()
        {
            ClientCatalog = mappingData.ClientCatalog
        });
    }
    return mappingListDb;
}

Insert table design

Insert Table

N Siva
  • 21
  • 1
  • 5

2 Answers2

0

I make a simple test based on your codes, you may refer to it:

var jsonmodel = new List<ApiJsonModel>
{
    new ApiJsonModel
    {
        Title = "Brown eggs",
        Type = "dairy",
        Description = "Raw organic brown eggs in a basket",
        Filename = "0.jpg",
        Height = 600,
        Width = 400,
        Price = 28.1M,
        Rating = 4
    }
};
var json = JsonConvert.SerializeObject(jsonmodel);
var SampleList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
        
var SampleDBList = new List<K360mapMaster>
{
    new K360mapMaster{ ClientCatalog = "Description"},
    new K360mapMaster{ ClientCatalog = "Price"}
};

foreach (var dicItem in SampleList)
{
    foreach(var item in dicItem)
    {
        if (!SampleDBList.Select(s => s.ClientCatalog).ToList().Contains(item.Key))
        {
            dicItem.Remove(item.Key);
        }
    }
}

Result:

enter image description here

Update:

DataTable dt = new DataTable();

var columnNames = SampleList.SelectMany(dict => dict.Keys).Distinct();
dt.Columns.AddRange(columnNames.Select(c => new DataColumn(c)).ToArray());
foreach (Dictionary<string, string> item in SampleList)
{
    var row = dt.NewRow();
    foreach (var key in item.Keys)
    {
        row[key] = item[key];
    }

    dt.Rows.Add(row);
}

return View("Index", dt);

Result:

enter image description here

mj1313
  • 7,930
  • 2
  • 12
  • 32
  • thanks for your kind support. Answer working fine in debugger. But i try to load final list as datatable and try to display in view. Its shows error: Specified argument was out of the range of valid values. (Parameter 'name') – N Siva Feb 22 '21 at 04:37
  • Hi @NSiva, I have never render a datatable at server side, but I think this [thread](https://stackoverflow.com/a/15296855/11965297) may help you. – mj1313 Feb 22 '21 at 05:35
  • Sure i will look it.Thanks for your valuable suggestion. Will you please help me one more thing. I need a linq insert query. I need to insert 2 columns from json and 4 columns are not null columns. I need to hardcoded column values or anyother way for not null columns.That table is already designed by some others. I am not able to change schema now. – N Siva Feb 22 '21 at 05:51
  • @NSiva, OK, I tested, and it can work, see my update – mj1313 Feb 22 '21 at 05:52
  • fine. Nice code for datatable. Display datatable is for sample testing only. Final major task is insert the selected values into another table. I have updated table design screenshot. We have only 2 values description and price. Whats is the best approach for inserting not null columns. – N Siva Feb 22 '21 at 06:03
  • What is your view code for return View("Index", dt); – N Siva Feb 22 '21 at 06:05
  • Since the datatable design can not change, I think there is no way but assign value to the not null columns, but these columns' value should not be hardcoding, they must be from somewhere. – mj1313 Feb 22 '21 at 06:12
  • Thanks for your valuable clarification. Will do the same. Will you please share me insert linq query.. – N Siva Feb 22 '21 at 06:20
  • Hi @NSiva, you may open a new thread to details the question, including the orm you use. – mj1313 Feb 22 '21 at 06:41
  • for final piece of code its not fair to create a new thread. Already 2 to 3 questions where asked to delete . – N Siva Feb 22 '21 at 15:06
  • from this list::: foreach (var dicItem in SampleList) { foreach(var item in dicItem) { if (!SampleDBList.Select(s => s.ClientCatalog).ToList().Contains(item.Key)) { dicItem.Remove(item.Key); } } } – N Siva Feb 22 '21 at 15:06
  • I need to insert 2 values desc,price and 2 hardcorded values to another table products. please share me linq insert query. i searched a lot but still didnt find anything dynamic. – N Siva Feb 22 '21 at 15:08
  • already 3 questions closed so far. So feel bad to start a new thread – N Siva Feb 22 '21 at 15:09
0

Model Class:

 public class ApiJsonViewModel
{
    //[JsonPropertyName("title")]
    public string Title { get; set; }

    //[JsonPropertyName("type")]
    public string Type { get; set; }

    //[JsonPropertyName("description")]
    public string Description { get; set; }

    //[JsonPropertyName("filename")]
    public string Filename { get; set; }

    //[JsonPropertyName("height")]
    public string Height { get; set; }

    //[JsonPropertyName("width")]
    public string Width { get; set; }

    //[JsonPropertyName("price")]
    public string Price { get; set; }

    //[JsonPropertyName("rating")]
    public string Rating { get; set; }
}

View:

@model System.Data.DataTable @using System.Data;

<table id="example" class="table table-bordered" style="width:100%">
    <thead>
        <tr>
            @foreach (DataColumn col in Model.Columns)
            {
                <th>@col.ColumnName</th>
            }
        </tr>
    </thead>
    <tbody>
        @foreach (DataRow row in Model.Rows)
        {
            <tr>
                @foreach (DataColumn col in Model.Columns)
                {
                    <td>@row[col.ColumnName]</td>
                }
            </tr>
        }
    </tbody>
</table>
<form method="post">
        <table class="table table-striped table-bordered" style="width:100%">
            <tr>
                <td align="center">
                    <button id="btnGetImportData" asp-action="GetImportData" class="btn btn-primary">Get ImportData</button>
                </td>
            </tr>
        </table>
    </form>

Controller:

 public class GetImportController : Controller
{
    private readonly K360ECommerceSContext _context;
    public GetImportController(K360ECommerceSContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {           
        var resultApiJsonProp = GetApiJsonProperties();
        DataTable dt = new DataTable();
        dt = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(resultApiJsonProp));
        return View(dt);
    }

    public List<ApiJsonViewModel> GetApiJsonProperties()
    {
        string strjsonUrl;
        using (WebClient client = new WebClient())
        {
            strjsonUrl = client.DownloadString("https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json");
        }
        List<ApiJsonViewModel> ListApiJsonProp = JsonConvert.DeserializeObject<List<ApiJsonViewModel>>(strjsonUrl);
        return ListApiJsonProp;
    }

  
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult GetImportData()
    {           
        var resultApiJsonProp = GetApiJsonProperties();
        var json = JsonConvert.SerializeObject(resultApiJsonProp);
        var SampleList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);

        List<K360mapMaster> mappingListDb = new List<K360mapMaster>();
        var query = from K360mapMaster in _context.K360mapMasters
                    select K360mapMaster;
        var mappings = query.ToList();
        if (mappings != null)
        {
            foreach (var mappingData in mappings)
            {
                mappingListDb.Add(new K360mapMaster()
                {
                    ClientCatalog = mappingData.ClientCatalog
                });
            }
        }

        foreach (var dicItem in SampleList)
        {
            foreach (var item in dicItem)
            {
                if (!mappingListDb.Select(s => s.ClientCatalog).ToList().Contains(item.Key))
                {
                    dicItem.Remove(item.Key);
                }
            }
        }
            DataTable dataTabledt = new DataTable();
            dataTabledt = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(SampleList));
            return View("Index",dataTabledt);
    }

    }
N Siva
  • 21
  • 1
  • 5