我在WCF中有一个Web服务,其操作需要JSON格式的请求和响应.我知道我可以编写具有我想用JSON表示的属性的C#对象,但我的问题是JSON参数可能会改变.例如,我的方法合同如下:
[WebInvoke(Method = "PUT",
UriTemplate = "users",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Response PutUserAccount(User user);
Run Code Online (Sandbox Code Playgroud)
用户的参数可能包含任意数量的参数,因此用户的实例有时可能是:
{
"Name" : "John",
"LastName" : "Doe",
"Email" : "jdoe@gmail.com",
"Username" : "jdoe",
"Gender" : "M"
"Phone" : "9999999"
}
Run Code Online (Sandbox Code Playgroud)
甚至:
{
"Name" : "John",
"LastName" : "Doe",
"Email" : "jdoe@gmail.com",
"Username" : "jdoe",
"FavoriteColor" : "Blue"
}
Run Code Online (Sandbox Code Playgroud)
使用具有可变数量属性的对象来表示JSON文档的最佳方法是什么?
编辑这个类允许我有一个灵活的JSON表示,因为我不能使用JObjectWCF(我应该发布这个作为答案吗?):
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
1510 次 |
| 最近记录: |