Return Json object with Duplicate Keys using C#

前端 未结 2 1257
慢半拍i
慢半拍i 2021-02-06 19:57

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 no

2条回答
  •  感动是毒
    2021-02-06 20:32

    No, this is not possible.

    This would be invalid* JSON:

    {
        "error" : {
            "SaveContactMethod":"FirstName Invalid",
            "SaveContactMethod":"LastName Invalid",
            "SaveContactMethod":"MiddleName Invalid"
        }
    }
    

    You can check this here:

    Warning:Duplicate key, names should be unique.[Code 23, Structure 9]
    Warning:Duplicate key, names should be unique.[Code 23, Structure 13]
    

    *Depending on what you call valid

    If you realy want to go this route, according to RFC 4627, you could use the StringBuilder class.


    Since you don't seem to understand, what Depending on what you call valid means.

    ECMA-262:

    In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.

    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.

提交回复
热议问题