【问题标题】:How to Serialize a JSON Parameter list of varied type and without names如何序列化不同类型且没有名称的 JSON 参数列表
【发布时间】:2013-11-29 11:49:19
【问题描述】:

我需要向包含以下 JSON 的服务器发布请求。我想在代表请求的类上使用 DataContractJsonSerializer 和 DataContract、DataMember 属性,例如

{"method":"mymethod","parameters":[10,"somestring"]}

这代表一个 RPC 调用

mymethod(10,"somestring"). 

在某些 API 中。 API中有很多不同参数列表的调用。

如果参数列表包含 T 类型的对象,我可以使用泛型 List<T>,这很简单,但 API 需要不同类型的参数列表(包括非原始对象)。

那么如何为参数数组构造 DataContract 呢?

【问题讨论】:

    标签: .net json datacontractjsonserializer


    【解决方案1】:

    所有参数都需要做字符串类型——会有参数的序列化值。 然后你需要这样做:

    using System;
    using System.IO;
    using System.Reflection;
    using System.Runtime.Serialization.Json;
    using System.Text;    
    namespace ConsoleApplication1
    {
    class Program
    {
        static void Main(string[] args)
        {
            string methodName = "test";
            MethodInfo methodInfo = typeof(ClassWithMethods).GetMethod(methodName);
            string[] parameters = new string[] { "1", "\"qwe\"", "{\"SomeProperty\":\"prop\"}" };
            object[] parameterValues = new object[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                DataContractJsonSerializer s = new DataContractJsonSerializer(methodInfo.GetParameters()[i].ParameterType);
                object p = s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(parameters[i])));
                parameterValues[i] = p;
            }
            methodInfo.Invoke(new ClassWithMethods(), parameterValues);
        }
    }
    
    public class ClassWithMethods
    {
        public void test(int i, string s, ComplexType ct)
        {
            Console.WriteLine("{0} {1} {2}", i, s, ct.SomeProperty);
        }
    }
    
    
    public class ComplexType
    {
        public string SomeProperty { get; set; }
    }
    }
    

    【讨论】:

    • 谢谢,但这是反序列化响应,这可能会有所帮助。我需要序列化参数。
    • MemoryStream ms = new MemoryStream(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(object[]), new Type[]{ typeof(ComplexType)}); serializer.WriteObject(ms, new object[]{1, "123", new ComplexType(){SomeProperty = "456"}}); ms.Position = 0; string v = new StreamReader(ms).ReadToEnd();
    • 你也可以使用 Json.net。这很简单,结果会更漂亮。 string res = JsonConvert.SerializeObject(new object[] {1, "123", new ComplexType() {SomeProperty = "456"}}); 结果:[1,"123",{"SomeProperty":"456"}]
    【解决方案2】:

    谢谢卢卡斯。所以稍微重述问题以包括复杂类型:-

    {"method":"mymethod","parameters":[10,"somestring",{SomeProperty:value}]}

    这表示对 JSON RPC 调用的调用 mymethod(int,string,ComplexProperty)

    The code is:-
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace JSONConsoleApplication4
    {
        class Program
        {
            [DataContract]
            public class ComplexType
            {
                [DataMember]
                public string SomeProperty { get; set; }
            }
    
            [DataContract]
            public class GenericRequest
            {
                [DataMember]
                public string method { get; set; }
                [DataMember]
                public object[] parameters { get; set; }
            }
    
    
            static void Main(string[] args)
            {
                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializerSettings settings = 
                    new DataContractJsonSerializerSettings() { EmitTypeInformation=EmitTypeInformation.Never, 
                                                               KnownTypes=new Type[] { typeof(ComplexType) } };
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GenericRequest),settings);
                serializer.WriteObject(ms, 
                    new GenericRequest() { method = "mymethod", 
                                           parameters = new object[] { 10, "somestring", new ComplexType() { SomeProperty="value"}} });
                ms.Position = 0;
                string v = new StreamReader(ms).ReadToEnd();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多