简体   繁体   English

如何序列化各种类型且没有名称的JSON参数列表

[英]How to Serialize a JSON Parameter list of varied type and without names

I need to post a request to a server containing the following JSON. 我需要将请求发布到包含以下JSON的服务器。 I want to use DataContractJsonSerializer and DataContract, DataMember attributes on the classes representing a request such as 我想在表示请求的类上使用DataContractJsonSerializer和DataContract,DataMember属性,例如

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

This represents an RPC call 这代表一个RPC调用

mymethod(10,"somestring"). 

in some API. 在某些API中。 There are many calls with different parameter lists in the API. API中有许多具有不同参数列表的调用。

This is straightforward if the parameter list contains objects of type T where I can use generic List<T> , but the API needs a list of parameters of different types (including non-primitive objects). 如果参数列表包含类型T的对象(我可以在其中使用通用List<T> )但API需要一个不同类型的参数列表(包括非原始对象),则这很简单。

So how can I construct the DataContract for the parameters array ? 那么如何为参数数组构造DataContract?

You need to do all parameters string type - there will be serialized values of parameters. 您需要完成所有参数的字符串类型-参数将有序列化的值。 Then you need to do like this: 然后,您需要这样做:

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; }
}
}

Thanks Lucas. 谢谢卢卡斯。 So slightly restating the question to include complex types:- 所以稍微重申一下这个问题,以包括复杂的类型:

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

This represents a call to JSON RPC call mymethod(int,string,ComplexProperty) 这表示对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();
        }
    }
}

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

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