我想將JSON序列化爲沒有鍵/值的正常格式,但不幸的是提供的類向JSON文件添加了鍵和值字符串。 這是帖子的方法:序列化SortedList到對象數組並刪除鍵/值
[TestMethod]
public void PostTest()
{
var request = new HttpRequestMessage();
request.Headers.Add("X-My-Header", "success");
MyCaseRequest data = new MyCaseRequest()
{
Name = "TestAgre",
ExpirationDateTime = "2016-07-14T00:00:00.000Z",
Signatories = new List<SignatoryRequest>
{
new MyRequest() { Type = MyType.Comp, Id = "11111" },
new MyRequest() { Type = MyType.Per, Id = "2222" }
},
Documents = new SortedList<string, ThingsRequest>()
{
{"0" , new ThingsRequest() { Name = "Test", Description = "Short description about", Length = 4523 }},
{"1" , new ThingsRequest() { Name = "Test1", Description = "short description about", Length = 56986 }}
}
};
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new DictionaryAsArrayResolver();
settings.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(data, settings);
var statusCode = sendJsonDemo.SendJsonDemo(json);
}
,這裏是我的類序列化排序的字典對象數組:
class DictionaryAsArrayResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) ||
(i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
{
return base.CreateArrayContract(objectType);
}
return base.CreateContract(objectType);
}
}
,這裏是我的輸出:
{
"Name": "TestAgreement",
"ExpirationDateTime": "2016-07-14T00:00:00.000Z",
"Signatories": [
{
"Type": "Comp",
"Id": "11111"
},
{
"Type": "Per",
"Id": "2222"
}
],
"Documents": [
{
"Key": "0",
"Value": {
"Name": "Test",
"Description": "Short description about",
"Length": 4523
}
},
{
"Key": "1",
"Value": {
"Name": "Test1",
"Description": "short description about",
"Length": 56986
}
}
],
"Metadata": []
}
看起來這是不是真的ASP.NET特有的,所以它如果你能提供一個[mcve]控制檯應用程序讓我們重現問題,那將是最好的。接下來,你已經顯示了你*的輸出*,這是有意義的,因爲'SortedList'是一個鍵/值映射,按鍵排序。你認爲它只是JSON數組嗎?如果是這樣,你應該使用'List <>'而不是'SortedList <,>'。 –