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
You have a classic "XY" problem. You have asked "How do I do X", but you really need to do Y and you think that X is the only way to get to Y -- but X is either impossible or very hard. By changing your requirements a little, you can get to Y a different way, but you haven't seen that yet since you're stuck on X.
Here's your X: the JSON format that you want to get:
{
"error" : {
"SaveContactMethod":"FirstName Invalid",
"SaveContactMethod":"LastName Invalid",
"SaveContactMethod":"MiddleName Invalid"
}
}
This will, as others have said, throw away all the error messages except for one when you load it into your C# code.
However, there's a very simple way to get all the error messages. You simply need to change the JSON you're expecting to look something like this instead:
{
"error" : {
"SaveContactMethod": [
"FirstName Invalid",
"LastName Invalid",
"MiddleName Invalid"
]
}
}
If you only had a single error message, you should still use a list:
{
"error" : {
"SaveContactMethod": [
"FirstName Invalid"
]
}
}
That way when you load the JSON into your C# code, it will always have the same type, Dictionary
, whether there was one error or many.
That's the Y in your XY problem. Instead of beating your head against the wall of "I want to have duplicate keys in JSON", find a way around the wall: have a single key with a list of values. And now you can do what you really needed, which is to get all the error messages from your form with just a single key name for every single error message.