简体   繁体   English

带有C#对象的数组值的JSON字典

[英]JSON dictionary with array values to C# object

I would like to know how to convert the following object to C# when reaching the mathod. 我想知道如何在到达mathod时将以下对象转换为C#。 I needed to create an object which can hold multiple array's within JSON something like the following 我需要创建一个可以在JSON中保存多个数组的对象,如下所示

{   
    "cars": {
        "Ferrari":["LaFerrari","F40","458"],
        "Porsche":["911","959"],
        "Lamborghini":["Aventador"]
    }
}

The code I used is the following within cshtml 我在cshtml中使用的代码如下

<div class="row">
    <div class="col-md-4">
        <div>
            <input type="text" id="txtKey" />
            <input type="button" id="btnKey" />
        </div>
        <div>
            <input type="text" id="txtChild" />
            <input type="button" id="btnChild" />
        </div>
        <div>
            <input type="button" id="btnSubmit" />
        </div>
    </div>
</div>

@section scripts
{
        $(function () {

            AddKeyToDictionary('Ferrari');
            AddKeyToDictionary('Porsche');
            AddKeyToDictionary('Lamborghini');

            AddValueToDictionary('Ferrari', 'LaFerrari');
            AddValueToDictionary('Ferrari', 'F40');
            AddValueToDictionary('Ferrari', '458');

            AddValueToDictionary('Porsche', '911');
            AddValueToDictionary('Porsche', '959');

            AddValueToDictionary('Lamborghini', 'Aventador');

            $('#btnKey').click(function () {
                AddKeyToDictionary($('#txtKey').val());
            });
            $('#btnChild').click(function () {
                AddValueToDictionary($('#txtKey').val(), $('#txtChild').val());
            });
            $('#btnSubmit').click(function () {
                submit();
            });

        });

        var dict = {};

        function AddKeyToDictionary(key) {
            dict[key] = [];
        }

        function AddValueToDictionary(key, value) {
            dict[key].push(value);
        }

        function submit() {

            var url = "@Url.Action("UpdateCustomFields", "Home")";

            var data = JSON.stringify({ 'cars': dict });

            $.ajax({
                type: "POST",
                contentType: "Application/json;charset=utf-8",
                url: url,
                data: data,
                datatype: "json",
                success: function (msg) {

                },
                error: function (request, status, error) {
                    displayDialog("A communication Error has occurred, please contact IT support: " + error);
                }
            });
        }


    </script>

}

I've tried the following within MVC (got this from a JSON c# convertor) 我在MVC中尝试过以下内容(从JSON c#convertor获取此内容)

public JsonResult UpdateCustomFields(RootObject cars)
        {
            return Json("");
        }

    }

    public class Cars
    {
        public List<string> Ferrari { get; set; }
        public List<string> Porsche { get; set; }
        public List<string> Lamborghini { get; set; }
    }

    public class RootObject
    {
        public Cars cars { get; set; }
    }

The car makes should be dynamic and then the arrays below should be converted correctly. 汽车制造应该是动态的,然后下面的阵列应该正确转换。

I also tried to iterate through the array and changed them all to key value pairs which still wasn't rendering 我还尝试迭代数组并将它们全部更改为仍未呈现的键值对

function convertToKeyValue() {
   submitValue = [];

    for (var k in dict) {
        if (dict.hasOwnProperty(k)) {
            if (dict[k].length > 0) {
                for (var i = 0; i < dict[k].length; i++) {    
                    submitValue.push({ key: k, value: dict[k][i] });
                }
            } else {
                submitValue.push({ key: k, value: '' });
            }
        }
    }
}

Passing them through the name/value pairs I was able to see them in the dynamic property within the controller but can't get to the variables. 通过名称/值对传递它我能够在控制器内的动态属性中看到它们但无法获取变量。

public JsonResult UpdateClientCustomFields(object cars)
{    
    var result = customFields.XmlSerializeToString();

    return Json("hello");
}

If anyone can help or point me in the right direction. 如果有人可以帮助或指出我正确的方向。

Thanks 谢谢

Updated: I've had to convert the javascript array to a list of key pairs (not ideal) and use List> cars as the paramter, the model is not ideal, but will use this until I find a better way. 更新:我必须将javascript数组转换为密钥对列表(不理想)并使用List> cars作为参数,模型不理想,但会使用它直到找到更好的方法。

Here is the updated code 这是更新的代码

HTML HTML

<input type="button" id="btnSubmit2" />

var submitValue = [];

function convertToKeyValue() {

    submitValue = [];

    for (var k in dict) {
        if (dict.hasOwnProperty(k)) {
            //alert("Key is " + k + ", value is" + dict[k]);
            //alert("KEY: " + k);

            if (dict[k].length > 0) {
                for (var i = 0; i < dict[k].length; i++) {
                    //alert("childrec: " + dict[k][i]);
                    submitValue.push({ key: k, value: dict[k][i] });
                }
            } else {
                submitValue.push({ key: k, value: '' });
            }
        }
    }

}

function submit2() {
    convertToKeyValue();

    var url = "@Url.Action("UpdateCustomFields2", "Home")";

    var data = JSON.stringify({ 'cars': submitValue });

    $.ajax({
        type: "POST",
        contentType: "Application/json;charset=utf-8",
        url: url,
        data: data,
        datatype: "json",
        success: function (msg) {

        },
        error: function (request, status, error) {

        }
    });
}

MVC MVC

public JsonResult UpdateCustomFields2(List<Dictionary<string, string>> cars)
{
    return Json("");
}

汽车模型

Try changing your cars property in RootObject to public Dictionary<string,List<string>> cars {get; set;} 尝试将RootObjectcars属性RootObjectpublic Dictionary<string,List<string>> cars {get; set;} public Dictionary<string,List<string>> cars {get; set;}

Try to make your input param as string and then deserialize it to your object. 尝试将输入参数作为字符串,然后将其反序列化为对象。

 public JsonResult UpdateCustomFields(string cars)
 {
     RootObject yourCars = JsonConvert.DeserializeObject<RootObject>(cars);

     return Json("");
 }

Good luck :) 祝好运 :)

Unless I am missing something, the following seems to work fine 除非我遗漏了什么,否则以下似乎工作正常

public class Program
{
    public void Main(string[] args)
    {
        var json = @"
            {   
                ""cars"": {
                    ""Ferrari"":[""LaFerrari"",""F40"",""458""],
                    ""Porsche"":[""911"",""959""],
                    ""Lamborghini"":[""Aventador""]
                }
            }
        ";

        var dataObj = JsonConvert.DeserializeObject<Data>(json);
    }

    public class Data
    {
        public Dictionary<string, List<string>> Cars { get; set; }
    }
}

Which version of JSON.NET are you using? 您使用的是哪个版本的JSON.NET? I remember older versions had issues with dictionaries, but you could probably just create your own converter if that is the case. 我记得旧版本的字典存在问题,但如果是这种情况,你可能只是创建自己的转换器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM