2

i would like use uknown object from JS like this

{"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'. This object has no permament keys, like this name "abcd 1" can be another name in future.

i have function Test(Object aa) and question is, what type i must use for unknown array of objects or strings. Thanks

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
MarTic
  • 665
  • 3
  • 10
  • 27
  • 2
    you can check out this. It works for me. http://stackoverflow.com/questions/4611031/convert-json-string-to-c-sharp-object – user952072 Sep 19 '13 at 06:44

4 Answers4

3

Have you tried this website before: http://json2csharp.com/ ?

Fernando Vezzali
  • 2,219
  • 1
  • 29
  • 32
  • That's exactly wrong. Keys can change their own name, therefore i can't use basic c# class. – MarTic Sep 19 '13 at 10:57
  • I wish there was a down vote for comments, geesh, thats exactly rude user1173536 and if you weren't looking for someone to just do it for you, customizing my code is the answer to your problem – Brian Ogden Sep 19 '13 at 16:23
2

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. 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.

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:

[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;
        }
    }
Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
  • Ok, and have you any other idea, to retrieve and passing dynamic structure of JSON? Like pass application/json to any other type like JObject, or dynamic type? I try change accept to application/json and add to function (dynamic data). Exists any structure, where i dynamicaly access to variable like this? Very Simple Example: dynamic data; Object aa = data.aa; String abcd2 = aa["abcd 2"]; – MarTic Sep 20 '13 at 05:48
1

For my personal experience, the most useful way to consume Json inside a code is to use dynamics. Basically, instead of serializing/deserializing to specific type, you convert json object to dynamic one.

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. Otherwise, there are lots of libraries for that specific purpose, like Json.Net

Dima
  • 6,721
  • 4
  • 24
  • 43
1

Finally I found solution. Use Newtonsoft.Json and this code as sample for dynamic data structure:

$.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])
              {

              }
          }
       }
    }

MarTic
  • 665
  • 3
  • 10
  • 27