I'm integrating our system with a 3rd party. They sent a JSON example of what they are expecting. The JSON does not seem right to me. The users object has an email address which looks like being used as a reference type's member name instead of value type's member name. In other words, should it not be an array of users, and each item in array would be the users object, with "email": "[email protected]" as one of the properties?
I am going to ask them but also wanted to check here if anyone else thinks there is an issue with this JSON
{
"users": {
“[email protected]”: {
"First_Name": "John",
"Last_Name": "Doe",
"Member_Id": "XX9008000",
"Mailing_Address": {
"Street": "P O Box 111 ",
"City": "Red City",
"State": "CA",
"Zip": "99999"
}
},
"enrollments": [
{
"Student": "[email protected]",
"Course_Ids": "369,370"
}
]
}
}
I'm using Newtonsoft.Json to convert C# object to JSON. The output is always of the format, reference type's type: reference type's property/value enumeration.
{"users":[{"name":"john","id":"a1"},{"name":"tom","id":"a2"}]}
or
{"users":{"user1":{"name":"john","id":"a1"},"user2":{"name":"tom","id":"a1"}}}
But it can never be:
{"users":{"a1":{"name":"john"},"a2":{"name":"tom"}}}
Because a1 and a2 are values of value type string Id
It may be valid JSON but can it be obtained through a serialization library code? Or will I have to manually construct it?
CodePudding user response:
Disregarding the quote type (that should be "<..>") here-> “[email protected]”, this is a valid JSON, and a common use for this type of object.
Instead of an array of object, the structure is the id of the object, and inside it, the object.
You need a Dictionary<string, object> where the Key is probably username (= email) and the Value is the user object.
CodePudding user response:
To the first question
should it not be an array of users?
this is a typical issue for varying json responses having either one or multiple elements.
To generate Json, it is good practice sticking with the so called Badger-Fish notation http://badgerfish.ning.com/ which states:
“Nested elements become nested properties” but “Multiple elements at the same level become array elements” therefore when there is one element, a property is displayed but in case of multiple elements an array is displayed".
Since there is only one "users" element and only one "enrollments" element at the same respective level, there shouldn't be any arrays declared.