我有一个Web方法返回一个List<AttributeCollection>。显然,AttributeCollection是一个包含每个属性值的属性列表(在本例中是由CRM2011SDK获取的)。
下面是该方法返回的JSON:
[
[
{
"Key": "mobilephone",
"Value": "(430) 565-1212"
},
{
"Key": "firstname",
"Value": "John"
}
],
[
{
"Key": "mobilephone",
"Value": "(430) 565-1313"
},
{
"Key": "firstname",
"Value": "Mark"
}
]
]现在,第一对括号是列表的可视化表示,然后每个AttributeCollection都有许多对括号(AttributeCollection)。
我想去掉第一对括号,将其替换为顶级元素名(即:allAttributes),然后是下面的所有项。
我对JsonMediaTypeFormatter的JsonMediaTypeFormatter方法做了过多的研究
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
if ((typeof(IEnumerable<AttributeCollection>).IsAssignableFrom(type)))
{
//anything I could do here ?
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
} 我曾想过要操作JSON字符串本身,但从那里看,它似乎是不可访问的。
有什么想法吗?
谢谢。
发布于 2014-05-28 21:37:06
如果要在格式化程序本身上执行此操作,则可能需要将包装代码写入writeStream,如下所示(在记事本中测试):
public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if ((typeof(IEnumerable<AttributeCollection>).IsAssignableFrom(type)))
{
var list = (IEnumerable<AttributeCollection>)value;
byte[] headerBytes = Encoding.UTF8.GetBytes("{\"allAttributes\":");
byte[] footerBytes = Encoding.UTF8.GetBytes("}");
writeStream.Write(headerBytes, 0, headerBytes.Length);
foreach (var item in list)
{
await base.WriteToStreamAsync(item.GetType(), item, writeStream, content, transportContext);
}
writeStream.Write(footerBytes, 0, footerBytes.Length);
}
else
{
return await base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}另一种选择是创建包装类并序列化它:
public class MyWrappingClass
{
public IEnumerable<AttributeCollection> allAttributes { get; set; }
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if ((typeof(IEnumerable<AttributeCollection>).IsAssignableFrom(type)))
{
var list = (IEnumerable<AttributeCollection>)value;
var obj = new MyWrappingClass { allAttributes = list };
return base.WriteToStreamAsync(obj.GetType(), obj, writeStream, content, transportContext);
}
else
{
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}https://stackoverflow.com/questions/23922154
复制相似问题