The data in JSON format is sent to api endpoint.
Data sample:
{
"templateId": "dc15e4d1-ccbd-4581-a819-5b7f90b32cc5",
"name": "abc",
"steps": [
{
"id": "34b4f406-120e-4d80-8018-6c780c80a6c4",
"visible": false,
}
]
}
Api gets data in this format:
public class TemplateRequest {
public Guid TemplateId { get; set; }
public string Name { get; set; }
public StepRequest[] Steps { get; set; }
}
StepRequest class:
public class StepRequest {
[ModelBinder(Name = "id")]
public Guid StepId { get; set; }
public bool? Visible { get; set; }
}
The JSON has id key instead of stepId, but I can't get it in controller.
When I check, the StepId is always an empty Guid.
What is wrong here, why the StepId property is not having the value from id key?
Yes, like #daremachine said, it was NewtonSoft and JsonProperty(PropertyName = "id") helped.
Related
I am developing an endpoint in C# to accept JSON posted from an external provider (Telnyx). Here is a sample of the data:
{
"data": {
"event_type": "fax.received",
"id": "e15c28d4-147e-420b-a638-2a2647315577",
"occurred_at": "2021-11-19T16:37:02.863682Z",
"payload": {
"call_duration_secs": 35,
"connection_id": "1771912871052051547",
"direction": "inbound",
"fax_id": "2a168c93-3db5-424b-a408-b70a3da625bc",
"from": "+12399999999",
"media_url": "https://s3.amazonaws.com/faxes-prod/999",
"page_count": 1,
"partial_content": false,
"status": "received",
"to": "+12399999999",
"user_id": "dc6e79fa-fe3b-462b-b3a7-5fb7b3111b8a"
},
"record_type": "event"
},
"meta": {
"attempt": 1,
"delivered_to": "https://webhook.site/27ef892c-c371-4976-ae22-22deea57080e"
}
}
I have verified this is valid JSON through https://jsonlint.com/. I created a model:
public class myDeserializedClass
{
public class Payload
{
public int call_duration_secs { get; set; }
public string connection_id { get; set; }
public string direction { get; set; }
public string fax_id { get; set; }
public string from { get; set; }
public string media_url { get; set; }
public int page_count { get; set; }
public bool? partial_content { get; set; }
public string status { get; set; }
public string to { get; set; }
public string user_id { get; set; }
}
public class Data
{
public string event_type { get; set; }
public string id { get; set; }
public DateTime occurred_at { get; set; }
public Payload payload { get; set; }
public string record_type { get; set; }
}
public class Meta
{
public int attempt { get; set; }
public string delivered_to { get; set; }
}
public class Root
{
public Data data { get; set; }
public Meta meta { get; set; }
}
}
The controller being posted to looks like:
[HttpPost]
public IActionResult InboundFax(myDeserializedClass json)
{
try
{
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(json.ToString().Trim());
return Content("OK");
}
catch(Exception ex)
{
return Content(ex.ToString());
}
}
I am receiving the error: Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: K. Path '', line 0, position 0. each time the API tries to post to my endpoint. I have also tried posting data using Postman and receive the same error message. Additionally, there are examples of JSON posting on the API website at https://developers.telnyx.com/docs/v2/programmable-fax/tutorials/receive-a-fax-via-api. Since my application fails with both postman and real-time API calls, I'm am working on the assumption the problem is my code, but can't be 100% certain and don't know how to fix it. This is a mission critical problem that I need to solve. Any help would be appreciated.
First of all, the class is bad. Should be:
public class Payload
{
public int call_duration_secs { get; set; }
public string connection_id { get; set; }
public string direction { get; set; }
public string fax_id { get; set; }
public string from { get; set; }
public string media_url { get; set; }
public int page_count { get; set; }
public bool? partial_content { get; set; }
public string status { get; set; }
public string to { get; set; }
public string user_id { get; set; }
}
public class Data
{
public string event_type { get; set; }
public string id { get; set; }
public DateTime occurred_at { get; set; }
public Payload payload { get; set; }
public string record_type { get; set; }
}
public class Meta
{
public int attempt { get; set; }
public string delivered_to { get; set; }
}
public class myDeserializedClass
{
public Data data { get; set; }
public Meta meta { get; set; }
}
It depends on the data that you are getting, but if you are getting the object, you don't need to convert it to work:
[HttpPost]
public IActionResult InboundFax(myDeserializedClass json)
{
try
{
//Work directly with json as object, forget "root" is: myDeserializedClass
return Content("OK");
}
catch(Exception ex)
{
return Content(ex.ToString());
}
}
or if you are getting the json as string:
[HttpPost]
public IActionResult InboundFax(string json)
{
try
{
//Work directly with json as object
myDeserializedClass myInstance= JsonConvert.DeserializeObject<myDeserializedClass>(json);
return Content("OK");
}
catch(Exception ex)
{
return Content(ex.ToString());
}
}
UPDATE AFTER TESTING IT:
I test it with a dummy controller:
[HttpPost]
public ActionResult InboundFax(myDeserializedClass json)
{
try
{
//Just dummy test
if (json.meta.attempt == 1)
{
return Content("OK");
}
else {
return Content("NO");
}
//Work directly with json as object, forget "root" is: myDeserializedClass
}
catch (Exception ex)
{
return Content(ex.ToString());
}
}
in a HomeController (blank template from MVC Web just dummy)
So posting to:
https://localhost:44334/Home/InboundFax
METHOD: POST
With the following data:
{
"data": {
"event_type": "fax.received",
"id": "e15c28d4-147e-420b-a638-2a2647315577",
"occurred_at": "2021-11-19T16:37:02.863682Z",
"payload": {
"call_duration_secs": 35,
"connection_id": "1771912871052051547",
"direction": "inbound",
"fax_id": "2a168c93-3db5-424b-a408-b70a3da625bc",
"from": "+12399999999",
"media_url": "https://s3.amazonaws.com/faxes-prod/999",
"page_count": 1,
"partial_content": false,
"status": "received",
"to": "+12399999999",
"user_id": "dc6e79fa-fe3b-462b-b3a7-5fb7b3111b8a"
},
"record_type": "event"
},
"meta": {
"attempt": 1,
"delivered_to": "https://webhook.site/27ef892c-c371-4976-ae22-22deea57080e"
}
}
Little quickwatch you see it map everything:
Could mean the POSTMAN is wrong configurated?
I use the following header:
Content-Type: application/json
I'm using TALEND API TESTER for Chrome, but every REST client is similar
With POSTMAN, same result, OK. Check for body: raw, type JSON, and header with the content type applicantion/json
Well, I am not sure if I have an answer or not, however, I did manage to get the application working by changing the endpoint to a WebApi instead of a MVC controller. I was under the impression a MVC controller could accept json data, however, I was unable to ever get it working. Once I changed it, everyting worked perfectly.
I am currently trying to progress with EF Core with a one-to-many (a user has many items). A tutorial or three later I managed to get things working with two very small and simple tables; however, I got a json exception: A possible object cycle was detected which is not supported which indicated that I had circular references.
Here is my code that gets around the issue using DTO objects, but is there a more cleaner way I can get around this issue as typing the, though it works, felt a bit wrong.
User:
namespace TestWebApplication.Database
{
public class User
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string Dob { get; set; }
public string Location { get; set; }
public ICollection<Items> Items { get; set; }
}
}
Items:
namespace TestWebApplication.Database
{
public class Items
{
[Key]
public int ItemId { get; set; }
public string Item { get; set; }
public string Category { get; set; }
public string Type { get; set; }
public virtual User User { get; set; }
}
}
DtoItems:
namespace TestWebApplication.Database.DTOs
{
public class DtoItems
{
public string Item { get; set; }
public string Category { get; set; }
public string Type { get; set; }
public DtoUser User { get; set; }
}
}
DtoUser:
namespace TestWebApplication.Database.DTOs
{
public class DtoUser
{
public string UserName { get; set; }
public string Dob { get; set; }
public string Location { get; set; }
}
}
TestController:
[HttpGet]
[Route("getitems")]
public ActionResult<List<Items>> GetItems()
{
List<Items> items = _myContext.Items.Include(i => i.User).ToList();
// DTOs
List<DtoItems> dtoItems = new List<DtoItems>();
foreach (var i in items)
{
var dtoItem = new DtoItems
{
Item = i.Item,
Category = i.Category,
Type = i.Type,
User = new DtoUser
{
UserName = i.User.UserName,
Dob = i.User.Dob,
Location = i.User.Location
}
};
dtoItems.Add(dtoItem);
}
return Ok(dtoItems);
}
The output from endpoint:
[
{
"item": "xxx",
"category": "xxx",
"type": "xxx",
"user": {
"userName": "xxx",
"dob": "xxx",
"location": "xx"
}
},
{
"item": "xxx",
"category": "xxx",
"type": "xxx",
"user": {
"userName": "xxx",
"dob": "xxx",
"location": "xxx"
}
}
]
In my opinion, the use of a DTO is the correct way of dealing with this issue. The fact that your datamodel does not serialize well is trying to hint to you that you should not be serializing your datamodel from the API at all.
I think returning a DTO also solves further issues down the road (What if you want to return all properties of the UserModel except one, maybe it's a sensitive property you don't want to just return from your API, what if your UserModel in the DB gets more navigation properties that you don't want to return?).
There is really only two other ways of handling this.
You can switch to Newtonsoft.Json which has support for handling reference loops and you can configure it one single line
Like so :
services.AddControllers().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
System.Text.Json does not have support for doing this (yet). Follow this Github Issue for more info : https://github.com/dotnet/runtime/issues/30820
You use the JsonIgnore attribute to force non serialization of properties which will work but... It looks weird to have an EntityFramework model have JSON Serialization options on it...
So your best bet, stick with the DTO.
More info :
https://dotnetcoretutorials.com/2020/03/15/fixing-json-self-referencing-loop-exceptions/
https://github.com/dotnet/runtime/issues/30820
https://www.newtonsoft.com/json/help/html/ReferenceLoopHandlingIgnore.htm
I have a WebApi returning the following JSON which I am trying to deserialize to the object below
JSON OBJECT
{
"results": [{
"id": 123456,
"fullName": "Foo Bar",
"localName": null,
"jobPosition": "ME",
"jobCompanyName": "EXTRA",
"jobLocationCountry": "United States of America",
"jobLocationCity": "San Francisco",
"jobCountrySubdivision": "California",
"boards": [],
"restrictionsIndicator": false,
"personRestriction": null,
"jobRestriction": null
}, {
"id": 789101,
"fullName": "Foo Bar",
"localName": null,
"jobPosition": null,
"jobCompanyName": "Unknown",
"jobLocationCountry": "Unknown",
"jobLocationCity": "Unknown",
"jobCountrySubdivision": "Unknown",
"boards": [{
"companyId": 667525,
"companyName": "FOO BAR COMPANY",
"companyOffLimits": null,
"restrictionCategoryId": null
}
],
"restrictionsIndicator": false,
"personRestriction": null,
"jobRestriction": null
}
],
"totalCount": 2,
"pageNumber": 1,
"resultsPerPage": 100
}
C# Classes
public class Rootobject
{
public Result[] results { get; set; }
public int totalCount { get; set; }
public int pageNumber { get; set; }
public int resultsPerPage { get; set; }
}
public class Result
{
public int id { get; set; }
public string fullName { get; set; }
public object localName { get; set; }
public string jobPosition { get; set; }
public string jobCompanyName { get; set; }
public string jobLocationCountry { get; set; }
public string jobLocationCity { get; set; }
public string jobCountrySubdivision { get; set; }
public Board[] boards { get; set; }
public bool restrictionsIndicator { get; set; }
public int? personRestriction { get; set; }
public int? jobRestriction { get; set; }
}
public class Board
{
public int companyId { get; set; }
public string companyName { get; set; }
public int? companyOffLimits { get; set; }
public object restrictionCategoryId { get; set; }
}
The DLL is a Portable Class Library which is .NET 4.5 and i have JSON.net(10.0.1) installed via nuget, but the portable library is connected to a xamarin IOS Project on a mac.
If the JSON being deserialized has no Boards it works out fine but if there is a Board then I receive the following message.
Unable to find a constructor to use for type Board. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'results[1].boards[0].companyId'
The Settings I am using are:
var settings = new Newtonsoft.Json.JsonSerializerSettings
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
};
I have tried the following ways to get it to serialize:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(_jsonString, settings);
var jobject = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(_jsonString, new Rootobject());
i have tried the following
Put in a default constructor
Naming all the parameters for the class in a constructor
Adding the Attribute to the constructor
Changing the Boards to a List
Taking out the Boards Property
but there is still no joy. It will not deserialize for me.
I think you have to modify this
public class Board
{
public int companyId { get; set; }
public string companyName { get; set; }
public int? companyOffLimits { get; set; }
public object restrictionCategoryId { get; set; }
**public Board(){}**
}
also in other classes
or also change
public Board[] boards { get; set; }
to
public List<Board> boards { get; set; }
Try....
There is a note in the developer road map from December of 2013 saying, "Lock/Unlock – We’ve added support for locking and unlocking files into the V2 API."
I've been all through the V2 API (for c#) and cannot find it anywhere. I expected to find something in the BoxFilesManager class or as something you would pass to UpdateInformationAsync within the BoxFileRequest class.
So is there a way to lock/unlock a file?
Great question. In order to see the current lock status of a file do a
GET https://api.box.com/2.0/files/7435988481/?fields=lock
If there is no lock on the file, you'll get something like this back:
{
"type": "file",
"id": "7435988481",
"etag": "0",
"lock": null
}
If you want to lock a file, you need to do a PUT (update) on the /files/ endpoint with a body that tells us what type of lock, and when to release it. Like this:
PUT https://api.box.com/2.0/files/7435988481/?fields=lock
{"lock": {
"expires_at" : "2014-05-29T19:03:04-07:00",
"is_download_prevented": true
}
}
You'll get a response confirming your lock was created:
{
"type": "file",
"id": "7435988481",
"etag": "1",
"lock": {
"type": "lock",
"id": "14516545",
"created_by": {
"type": "user",
"id": "13130406",
"name": "Peter Rexer gmail",
"login": "prexer#gmail.com"
},
"created_at": "2014-05-29T18:03:04-07:00",
"expires_at": "2014-05-29T19:03:04-07:00",
"is_download_prevented": true
}
}
Since there isn't a lock/unlock yet, I created a Lock Manager based on the existing managers:
class BoxCloudLockManager : BoxResourceManager
{
#region Lock/Unlock Classes
[DataContract]
internal class BoxLockRequestInfo
{
[DataMember(Name = "status")]
public string Status { get; set; }
//[DataMember(Name = "expires_at")]
//public string ExpiresAt { get; set; }
[DataMember(Name = "is_download_prevented")]
public bool IsDownloadPrevented { get; set; }
}
[DataContract]
internal class BoxLockRequest
{
[DataMember(Name = "lock")]
public BoxLockRequestInfo Lock { get; set; }
}
#endregion
const string LockFileString = "{0}/?fields=lock";
public BoxCloudLockManager(IBoxConfig config, IBoxService service, IBoxConverter converter, IAuthRepository auth)
: base(config, service, converter, auth)
{
}
public async Task<BoxLockInfo> LockAsync(string documentId,bool isDownloadPrevented = true)
{
var lockRequest = new BoxLockRequest { Lock = new BoxLockRequestInfo { Status = "lock", IsDownloadPrevented = isDownloadPrevented } };
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(LockFileString, documentId))
.Method(RequestMethod.Put)
.Payload(_converter.Serialize(lockRequest));
IBoxResponse<BoxLockInfo> response = await ToResponseAsync<BoxLockInfo>(request).ConfigureAwait(false);
return response.ResponseObject;
}
public async Task<BoxLockInfo> UnlockAsync(string documentId)
{
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(LockFileString, documentId))
.Method(RequestMethod.Put)
.Payload("{\"lock\":null}");
IBoxResponse<BoxLockInfo> response = await ToResponseAsync<BoxLockInfo>(request).ConfigureAwait(false);
return response.ResponseObject;
}
public async Task<BoxLockInfo> GetLockInfoAsync(string documentId)
{
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(LockFileString, documentId))
.Method(RequestMethod.Get);
IBoxResponse<BoxLockInfo> response = await ToResponseAsync<BoxLockInfo>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
I derived a class from BoxClient, adding a LockManager and instantiate it within the Constructor.
Here is the Lock Info:
[DataContract]
public class BoxLockedBy
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "login")]
public string Login { get; set; }
}
[DataContract]
public class BoxLockDetails
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "created_by")]
public BoxLockedBy CreatedBy { get; set; }
[DataMember(Name = "created_at")]
public string CreatedAt { get; set; }
[DataMember(Name = "expires_at")]
public string ExpiresAt { get; set; }
[DataMember(Name = "is_download_prevented")]
public bool IsDownloadPrevented { get; set; }
}
[DataContract]
public class BoxLockInfo
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "etag")]
public string Etag { get; set; }
[DataMember(Name = "lock")]
public BoxLockDetails LockDetails { get; set; }
}
I am receiving a FormatException when trying to load a an Album document from the default RavenDB database:
using (var session = _documentStore.OpenSession())
{
var album = session.Load<Album>(500);
//....
}
The Album JSON document in the database looks like this:
{
"AlbumArtUrl": "/Content/Images/placeholder.gif",
"Genre": {
"Id": "genres/10",
"Name": "Classical"
},
"Price": 8.99,
"Title": "The Best of Beethoven",
"CountSold": 0,
"Artist": {
"Id": "artists/203",
"Name": "Nicolaus Esterhazy Sinfonia"
}
}
And my in-memory entity Album class looks like this:
public class Album
{
public long Id { get; set; }
public string AlbumArtUrl { get; set; }
public DenomralizedGenre Genre { get; set; }
public decimal Price { get; set; }
public string Title { get; set; }
public int CountSold { get; set; }
public DenomralizedArtist Artist { get; set; }
}
public class DenomralizedGenre
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DenomralizedArtist
{
public int Id { get; set; }
public string Name { get; set; }
}
What am I doing wrong here?
Make all your Id strings. You have them as int and long. In RavenDB Id's are strings.
The Id as a string would be Album/24 in RavenDB. The Class name or type plus the HiLo value (created by the client tools) make up the Id.