使用C#返回具有重复键的Json对象 [英] Return Json object with Duplicate Keys using C#
问题描述
我正在使用WEB API来接收来自客户端应用程序的保存联系信息的请求,并且仅当数据有错误时才需要发送错误消息,否则什么也没有做。
I'm using WEB API to receive the request from the Client application to save the Contact Information and I need to send the Error Message only if data has an error otherwise nothing TODO
我早先使用过词典
例如:
Dictionary<string, string> error = new Dictionary<string, string>
{
{"SaveContactMethod_1", "FirstName Invalid"},
{"SaveContactMethod_2", "LastName Invalid"},
{"SaveContactMethod_3", "MiddleName Invalid"},
}
相应的JSON对象为
{
"error" : {
"SaveContactMethod_1":"FirstName Invalid",
"SaveContactMethod_2":"LastName Invalid",
"SaveContactMethod_3":"MiddleName Invalid"
}
}
但是我需要一个唯一键(即重复键),所以我将 Dictionary< string,string>
更改为 List< KeyValuePair< string,string> ;>
But I need an UNIQUE Key (i.e., Duplicate Key), So I changed the Dictionary<string, string>
to List<KeyValuePair<string, string>>
List<KeyValuePair<string, string>> error = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("SaveContactMethod", "FirstName Invalid"),
new KeyValuePair<string, string>("SaveContactMethod", "LastName Invalid"),
new KeyValuePair<string, string>("SaveContactMethod", "MiddleName Invalid"),
}
相应的JSON对象是
{
"error" : [
{ "key":"SaveContactMethod", "value":"FirstName Invalid" },
{ "key":"SaveContactMethod", "value":"LastName Invalid" },
{ "key":"SaveContactMethod", "value":"MiddleName Invalid" }
]
}
我的要求:我需要添加重复键,并且需要像字典一样的Json输出。
My Requirement: I need to add a Duplicate Key and I need the Json Output as like Dictionary. Kindly assist me.
预期输出:JSON
{
"error" : {
"SaveContactMethod":"FirstName Invalid",
"SaveContactMethod":"LastName Invalid",
"SaveContactMethod":"MiddleName Invalid"
}
}
推荐答案
否,这是不可能的。
这将无效* JSON:
This would be invalid* JSON:
{
"error" : {
"SaveContactMethod":"FirstName Invalid",
"SaveContactMethod":"LastName Invalid",
"SaveContactMethod":"MiddleName Invalid"
}
}
您可以选中此处:
Warning:Duplicate key, names should be unique.[Code 23, Structure 9]
Warning:Duplicate key, names should be unique.[Code 23, Structure 13]
如果确实要遵循这条路线,则根据RFC 4627,可以使用 StringBuilder
类。
由于您似乎不明白,所以取决于您所说的有效是什么意思。
Since you don't seem to understand, what Depending on what you call valid means.
如果对象中存在重复的名称字符串,则
会在词法上指向同一键的值
In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.
这意味着:如果得到三个 SaveContactMethod
,则只需要ECMA脚本(JS)中的中间名无效
。使用c#序列化,这甚至是不可能的。您需要为此编写自己的JsonSerializer。
That means: If you get three SaveContactMethod
's, you only want "MiddleName Invalid"
in ECMA Script (JS). With c# serialization, this would not even be possible. You need to write your own JsonSerializer for it.
这篇关于使用C#返回具有重复键的Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!