简体   繁体   English

将JSON转换为C#类型

[英]Convert JSON to C# type

i would like use uknown object from JS like this 我想使用JS这样的未知对象

{"aa":{"abcd 1":{"uio":[],"uio2":[],"uio3":["opee1","opee2","opee3"]},"abcd 2":null,"abcd 3":null,"abcd 4":null}} {“aa”:{“abcd 1”:{“uio”:[],“uio2”:[],“uio3”:[“opee1”,“opee2”,“opee3”]},“abcd 2”: null,“abcd 3”:null,“abcd 4”:null}}

sent into MVC with contentType 'application/json'. 发送到具有contentType'application / json'的MVC中。 This object has no permament keys, like this name "abcd 1" can be another name in future. 该对象没有固定密钥,例如该名称“ abcd 1”将来可能会成为另一个名称。

i have function Test(Object aa) and question is, what type i must use for unknown array of objects or strings. 我有功能测试(对象aa)和问题是,我必须使用什么类型的未知数组的对象或字符串。 Thanks 谢谢

你之前尝试过这个网站: http//json2csharp.com/

Though the ASP.NET 4.0 built in JSON to C# parsing/serialization works great and in most cases you can just define a simple C# class that models the "signature" of your JSON and get the correct C# representation of your JSON with a call to something like Test(MyCSharpJsonObj aa), you seem to need something more robust. 尽管内置JSON到C#进行解析/序列化的ASP.NET 4.0很好用,并且在大多数情况下,您可以定义一个简单的C#类来为JSON的“签名”建模,并通过调用来获取JSON的正确C#表示形式像Test(MyCSharpJsonObj aa)这样的东西,你似乎需要更强大的东西。 Note with the code you are about to see below, don't think you can overload your functions like so Test(ListData1 aa), Test(ListData2 aa) , ASP.NET won't correctly call the right function for you on request from client and may not even compile correctly, if using Web API, not sure. 请注意下面将要看到的代码,不要认为您可以像这样重载函数,例如Test(ListData1 aa), Test(ListData2 aa) ,ASP.NET不会根据您的请求正确为您调用正确的函数客户端甚至可能无法正确编译,如果使用Web API,不确定。

You more likely will have to call the right function from the client who is intimate with the JSON being sent in the request like so: Test1(ListData1 aa), Test2(ListData2 aa) using the code like below to assist you: 您更有可能必须从客户端调用正确的函数,该客户端与请求中发送的JSON密切相关,如下所示: Test1(ListData1 aa), Test2(ListData2 aa)使用如下代码来帮助您:

[Serializable]
        [DataContract]
        public class ListData1
        {
            [DataMember]
            public string r0 { get; set; }
            [DataMember]
            public string r1 { get; set; }
            [DataMember]
            public string r2 { get; set; }
            [DataMember]
            public List<Data1> optdata { get; set; }

            public ListData1() { }

            public string ToJson()
            {
                return JSONHelper.Serialize<ListData1>(this);
            }
        }

   [Serializable]
        [DataContract]
        public class Data1
        {
            [DataMember]
            public string label { get; set; }
            [DataMember]
            public string d0 { get; set; }
            [DataMember]
            public string d1 { get; set; }

            public Data1() { }

            public string ToJSON()
            {
                return JSONHelper.Serialize<Data1>(this);
            }
        }
        [Serializable]
        [DataContract]
        public class ListData2
        {
            [DataMember]
            public string r0 { get; set; }
            [DataMember]
            public string r1 { get; set; }
            [DataMember]
            public string r2 { get; set; }
            [DataMember]
            public List<Data2> optdata { get; set; }

            public ListData2() { }

            public string ToJson()
            {
                return JSONHelper.Serialize<ListData2>(this);
            }
        }

 [Serializable]
        [DataContract]
        public class Data2
        {
            [DataMember]
            public string label { get; set; }
            [DataMember]
            public string d0 { get; set; }
            [DataMember]
            public string d1 { get; set; }
            [DataMember]
            public string d2 { get; set; }

            public Data2() { }

            public string ToJSON()
            {
                return JSONHelper.Serialize<Data2>(this);
            }
        }

 public static class JSONHelper
    {
        public static string Serialize<T>(T obj)
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, obj);
            string retVal = Encoding.UTF8.GetString(ms.ToArray());
            return retVal;
        }

        public static T Deserialize<T>(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return default(T);
            }
            T obj = Activator.CreateInstance<T>();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms);
            ms.Close();
            return obj;
        }
    }

For my personal experience, the most useful way to consume Json inside a code is to use dynamic s. 以我的个人经验,在代码中使用Json的最有用方法是使用dynamic Basically, instead of serializing/deserializing to specific type, you convert json object to dynamic one. 基本上,您无需将序列化/反序列化为特定类型,而是将json对象转换为动态对象。

In this case you loose compile time validation, but get ability to support of any document structure. 在这种情况下,您将失去编译时验证,但能够支持任何文档结构。

In MVC4 you may use build-in Json.Decode() method from System.Web.Helpers.dll which will return you dynamic object. 在MVC4中,您可以使用System.Web.Helpers.dll中的Json.Decode()方法,该方法将返回动态对象。 Otherwise, there are lots of libraries for that specific purpose, like Json.Net 否则,有许多用于特定目的的库,如Json.Net

Finally I found solution. 最后我找到了解决方案 Use Newtonsoft.Json and this code as sample for dynamic data structure: 使用Newtonsoft.Json和此代码作为动态数据结构的示例:

$.ajax({
  ...
  data: {data: JSON.stringify({first: "name", next: ["a", "b"], last: {o: "in"}})}
})
[HttpPost]
    public JsonResult SaveMenu(String data)
    {
       dynamic JData = JObject.Parse(data);
       //--now JData.first == "name"
       if (JData.last is JObject)
       {

       }

       //--or dynamic foreach
       foreach (dynamic own in JData)
       {
          //--own.Name == first, next and last
          //--access to variable == JData[own.Name]
          if (JData[own.Name] is JArray)
          {
              foreach (String var in JData[own.Name])
              {

              }
          }
       }
    }

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

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