在C#中使用可变参数表示JSON的类的最佳方法
发布时间:2020-12-15 05:39:56 所属栏目:百科 来源:网络整理
导读:我在WCF中有一个Web服务,其操作需要 JSON格式的请求和响应.我知道我可以编写具有我想用JSON表示的属性的C#对象,但我的问题是JSON参数可能会改变.例如,我的方法合同如下: [WebInvoke(Method = "PUT",UriTemplate = "users",RequestFormat = WebMessageFormat
我在WCF中有一个Web服务,其操作需要
JSON格式的请求和响应.我知道我可以编写具有我想用JSON表示的属性的C#对象,但我的问题是JSON参数可能会改变.例如,我的方法合同如下:
[WebInvoke(Method = "PUT",UriTemplate = "users",RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)] [OperationContract] Response PutUserAccount(User user); 用户的参数可能包含任意数量的参数,因此用户的实例有时可能是: { "Name" : "John","LastName" : "Doe","Email" : "jdoe@gmail.com","Username" : "jdoe","Gender" : "M" "Phone" : "9999999" } 甚至: { "Name" : "John","FavoriteColor" : "Blue" } 使用具有可变数量属性的对象来表示JSON文档的最佳方法是什么? 编辑这个类允许我有一个灵活的JSON表示,因为我不能在WCF中使用JObject(我应该发布这个作为答案吗?): using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace MyNamespace { [Serializable] public class Data : ISerializable { internal Dictionary<string,object> Attributes { get; set; } public Data() { Attributes = new Dictionary<string,object>(); } public Data(Dictionary<string,object> data) { Attributes = data; } protected Data(SerializationInfo info,StreamingContext context) : this() { SerializationInfoEnumerator e = info.GetEnumerator(); while (e.MoveNext()) { Attributes[e.Name] = e.Value; } } public void GetObjectData(SerializationInfo info,StreamingContext context) { foreach (string key in Attributes.Keys) { info.AddValue(key,Attributes[key]); } } public void Add(string key,object value) { Attributes.Add(key,value); } public object this[string index] { set { Attributes[index] = value; } get { if (Attributes.ContainsKey(index)) return Attributes[index]; else return null; } } } } 解决方法
您可以使用
Json.NET中的JObject类.您可以将json解析为JObject属性并对其进行操作. JObject不仅仅是一本词典.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |