I am developing a .NET 6 web service (with Startup), one of methods is
public async Task<ActionResult> PutDirector([FromBody] Director director, CancellationToken cancellationToken)
{
var title = nameof(PutDirector);
// ....
}
Using Swagger I pass this JSON:
{
"id": 2,
"firstName": "Yeh",
"lastName": "Dobedo",
"title": "Mr",
"birthDate": "1983-09-18",
"address": "15 Book Street",
"search_Permission": true
}
It works fine.
By design I need to store json in the field address, i.e. a client app will parse and process this sub-json.
But when I pass
{
"id": 2,
"firstName": "Yeh",
"lastName": "Dobedo",
"title": "Mr",
"birthDate": "1983-09-18",
"address": "[
{
'line1': '15 Book Street',
'line2': '21 Book Street'
}
],",
"search_Permission": true
}
the method in the controller receives Director
object == null
.
I understand that JSON cannot be deserialized to object. How to pass JSON where string contains json?
2
Answers
your json is not valid, if you want to treat an address object as a string, you need this json
or a string as an object ( remove extra "")
but I would advice to create a json custom converter
While I prefer @Serge’s answer above, I wanted to point out another option for dealing with strings that are sometimes very difficult to use escape codes on.
For this to work, the client side has to understand what it is receiving. Most of the time, this means that you are writing both the service and the client code.
Difficult to escape strings can be converted to a non json strings. There are a lot of ways to do this, but a 64 bit string is pretty easy.
To encode a string named addressJson:
The encoded string (your address json from above) looks like this:
WwogICAgICAgewogICAgICAgIFwibGluZTFcIjogXCIxNSBCb29rIFN0cmVldFwiLAogICAgICAgIFwibGluZTJcIjogXCIyMSBCb29rIFN0cmVldFwiCiAgICAgIH0KICAgIF0=
To decode on the client side:
Its a little more tricky to decode because the string encoding isnt assumed, but, as you can see above, it’s still pretty easy.
The downside to this method is that the data in your json is not easily human readable anymore, but this may or may not matter to you.