Cannot deserialize the current JSON object while posting relational data - json

Ok there are a lot of questions and answers with this, if you know an exact duplicate of this please point me there but I am too dumb to understand how to make it work.
I want to add a worker to a job and everything is good until reaches ModelState. Here are the steps I am doing.
Filling the form
I submit the form and console breakpoint.
Name = "test", Description = "test",
worker = {Id: 21, FirstName: "Will", LastName: "Smith", Job: null}
Angular service in console
jobs = {Name: "test", Description: "test", worker: {…}}
Not sure why the dots in the brackets.
Reaches API method and fails modelstate.
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
In browser console I get:
Message:"The request is invalid."
ModelState:job.worker.Id:["Cannot deserialize the current JSON object (e.g. {…N object. Path 'worker.Id', line 1, position 16."]
Full error message from ModelState is:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.ICollection`1[TestRotaru.Models.Worker]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be deserialized from a JSON
object. JsonObjectAttribute can also be added to the type to force it
to deserialize from a JSON object. Path 'worker.Id', line 1, position
51.
Alright so far this is like a duplicate question but I tried few things and I don't understand some things in answers.
I tried to decorate my models with attributes such as:
These on top of the class
//[Serializable]
//[DataContract(IsReference = true)]
//[JsonObject(MemberSerialization.OptIn)]
On properties
//[JsonProperty]
Now the thing I have no clue and I don't understand:
var dict = JsonConvert.DeserializeObject
<Dictionary<string, Item>>(*Where this string comes from*);
This is just an example, I am concerned about that string in brackets not about if is a Dictionary or something else.
Here is my method:
[ResponseType(typeof(Job))]
public IHttpActionResult PostJob(Job job)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
job.DueDate = DateTime.Now;
db.Job.Add(job);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = job.Id }, job);
}
In all the answers about this everyone has that random json string in the round brackets... From where I am supposed to have that?
Here are my models:
Job Model:
//[Serializable]
//[DataContract(IsReference = true)]
//[Serializable()]
//[JsonObject(MemberSerialization.OptIn)]
public class Job
{
[JsonProperty]
public int Id { get; set; }
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public string Description { get; set; }
[JsonProperty]
public DateTime DueDate { get; set; }
[JsonProperty]
public bool IsCompleted { get; set; }
//[JsonProperty]
//[System.Runtime.Serialization.IgnoreDataMember]
public virtual ICollection<Worker> Worker { get; set; }
}
Worker Model:
//[Serializable]
//[DataContract(IsReference = true)]
//[JsonObject(MemberSerialization.OptIn)]
public class Worker
{
[JsonProperty]
public int Id { get; set; }
[JsonProperty]
public string FirstName { get; set; }
[JsonProperty]
public string LastName { get; set; }
//[JsonProperty]
//[System.Runtime.Serialization.IgnoreDataMember]
public virtual ICollection<Job> Job { get; set; }
}
Angular component and service:
add(Name: string, Description: string, worker): void {
this.jobsServices.addJob({Name, Description, worker } as Jobs)
.subscribe(jobs => {
this.jobs.push(jobs);
});
}
addJob(jobs: Jobs): Observable<Jobs> {
return this.http.post<Jobs>(this.apiURL, jobs, httpOptions);
}
div class="row">
<div class="col-md-12">
<label class="labelInputs">Select Worker</label><br>
<select [(ngModel)]="worker" class="form-control">
<option [value]="0">Select Worker</option>
<option *ngFor="let worker of workers" [ngValue]="worker">{{worker.FirstName}} {{worker.LastName}}</option>
</select>
</div>
<button class="brn btn-lg btn-block btn-change" (click)="add(name.value, desc.value, worker)">Add Job</button>
Alright is a long question but I wanted to prove myself I did my research and I just didn't thrown the error message and ask for solutions but this is really getting on my nerves.
Since I am posting relational data and my console shows ModelState{job.worker.Id: [,…]} how do I deserialize this? Plus my ModelState shows the worker as null when reaches the API, I can guess because is not converted from json, but worth to know.
Thank you for help.

So, the issue is that on your SPA you are sending worker as a single object and your API expects a list (array) of workers. Now I don't know what you want.. but you can either fix it by changing your API model to expect a single worker or change your SPA to send a list of workers. That no one can answer you.. depends on your app's requirements. But, my best guess is that a Job might have several workers. So:
Api Models (mostly the same.. just removed the attributes and changed Worker to Workers):
public class Job
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime DueDate { get; set; }
public bool IsCompleted { get; set; }
public virtual ICollection<Worker> Workers { get; set; }
}
public class Worker
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// This is an "array". your spa needs to send in this format.
public virtual ICollection<Job> Job { get; set; }
}
Spa Code:
export class Job {
id: int;
name: string;
// other fields here..
// Workers property that maps API model
workers: Array<Worker>;
constructor(id: int, name: string [other fields..]) {
this.id = id;
// and so on..
}
public addWorker(worker) {
this.workers.push(worker);
}
}
export class Worker {
id: int;
firstName: string;
// other fields here.. No need for array of jobs here!
}
With this model, you can do this before calling the API (on add function):
add(Name: string, Description: string, worker: Worker): void {
// creates a job using constructor
const job = new Job(name, description);
// add Job via function(can even be more complex and add validation and so on..)
job.addWorker(worker);
this.jobsServices.addJob(job)
.subscribe(jobs => {
this.jobs.push(jobs);
});
}
This will call the api with a json like this:
{
"id": 1,
"name": "some name",
[ other fields..]
"workers": [
{ "id:" 1, "name": "some worker name" }
]
}

Related

Cannot Get JsonConvert.DeserializeObject with oData to Work

I a class that looks like so:
public class AccountAddress
{
[Key]
public int accountNumber { get; set; }
public int rowNumber { get; set; }
public string civicaddress { get; set; }
public AccountAddress()
{
//Default constructor
}
}
There is a rest API that returns a List of AccountAddress as oData that looks like this to a variable "result":
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/Values.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#Values.Classes.Entities.AccountAddress","accountNumber":123456,"rowNumber":0,"civicaddress":"123 FAKE EAST DRIVE"
},{
"#odata.type":"#Values.Classes.Entities.AccountAddress","accountNumber":123457,"rowNumber":0,"civicaddress":"123 FAKE WEST DRIVE"
}
]
}
When I try to use:
var addressAccountLookup = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AccountAddress>>(result);
I get an error
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ATPublicTAX.Regina.ca.Values.Classes.Entities.AccountAddress]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Any help on this would be greatly appreciated.
Thanks.
You're passing the entire object to your deserialization method. You need to pass only the array, which is what it's asking you to do.
JArray array = (JArray) result["value"];
var addressAccountLookup = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AccountAddress>>(array);
Something like that should work.
The solution that I got to work is create a class:
private class oDataResponse<T>
{
public List<T> Value { get; set; }
}
Then deserialize like this:
var oDataRespone = Newtonsoft.Json.JsonConvert.DeserializeObject<oDataResponse<AccountAddress>>(result);

Custom serialization in Service Stack using DeSerializeFn

In servicestack, I am trying to process a webhook which sends the following JSON body to a service stack endpoint:
{
"action": "actionType1",
"api_version": "1.00",
"data": {
"id": "a8d316b8-10a7-4440-a836-9bd354f656db",
//VARIABLE other properties / structure
}
}
Which I am trying to map to the following request object:
[Route("/public/Webhookhandler", HttpVerbs.Post)]
public class MyCustomRequst
{
public string action { get; set; }
public string api_version { get; set; }
public string data { get; set; } //Will be the remaining JSON
}
However, when the service stack framework processes this - the value in "data" is the correct part of the JSON body, but with all of the quotes removed - so it is no longer valid.
I have tried to override the serialization for the whole request object using something like this:
JsConfig<MyCustomRequst>.DeSerializeFn = DeserializeMyRequestDto;
public MyCustomRequst DeserializeMyRequestDto(string rawBody)
{
var result = rawBody.FromJson<MyCustomRequst>();
return result
}
But even in this case, the value of the "rawBody" variable is still the correct JSON data but with all the quotes removed, e.g.
{
action:actionType1,
api_version:1.00,
data:{id:a8d316b8-10a7-4440-a836-9bd354f656db}
}
Am I doing something wrong here? I am unsure whether I am trying to make service stack do something it is not intended to do, or whether I am missing something that would make this work.
Any help would be appreciated :-)
Your DTO should closely match the shape of the JSON, if it's always a flat object you can use a string Dictionary, e.g:
[Route("/public/Webhookhandler", HttpVerbs.Post)]
public class MyCustomRequst
{
public string action { get; set; }
public string api_version { get; set; }
public Dictionary<string,string> data { get; set; }
}
If it's a more nested object structure you can use a JsonObject for a more flexible API to parse dynamically.

JSON array is converting to a generic list, but not converting to a generic collection. Why?

I am sending a Json Array from the client web application to asp.net webapi.
For example,
{
"SurveyId":3423,
"CreatorId":4235,
"GlobalAppId":34,
"AssociateList":[
{"AssociateId":4234},
{"AssociateId":43},
{"AssociateId":23423},
{"AssociateId":432}
],
"IsModelDirty":false,
"SaveMode":null
}
Here Associate List is a JSON Array,
Usually it will automatically serialize to a List<> object.
Using the below code ,i am posting the response to the WebApi
public IEnumerable<Associate> Post(ResponseStatus responseStatus)
{
return this.responsestatusrepository.ResponseStatusCheck(responseStatus);
}
The ResponseStatus class is shown below.
public class ResponseStatus : AppBaseModel
{
public int SurveyId { get; set; }
public int CreatorId { get; set; }
public int GlobalAppId { get; set; }
public List<Associate> AssociateList { get; set; }
}
I have changed the List<> to Collection<> as a part of my code analysis correction.
ie, public Collection<Associate> AssociateList { get; set; }
But it is always getting a null value when we are using collection instead of List. Is there any specific reason for this?
Ok, I think I will have to answer this in an indirect way.
What you are passing on to the server is an array of objects (in JSON format), but once you start processing this in C# the array of objects is now treated as a single c# object. Inside this object, your model expects one of the fields to be a Collection of Associate.
Right, when I work with JSON data similar to whats mentioned in this case - I prefer to use Newtonsofts' JOject.
So here is how I made the C# object with the JSON data you provided:
Used your model:
public class ResponseStatus
{
public int SurveyId { get; set; }
public int CreatorId { get; set; }
public int GlobalAppId { get; set; }
public Collection<Associate> AssociateList { get; set; }
}
public class Associate
{
public int AssociateId { get; set; }
}
Made a routine which takes string (the JSON data), and returns an object of type ResponseStatus:
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
---------------------------------------------------------------------
public static ResponseStatus GetResponseStatusObject(string jsonData)
{
JObject jObject = JObject.Parse(jsonData);
return jObject.ToObject<ResponseStatus>();
}
Now when I call this method and pass on the exact same JSON data which you provided, I get this:
This might not directly solve your problem, but hopefully guide you in the right direction in understanding array/object serialization when working with JavaScript/C#.
Best of luck!

How to read this Json to controller object? Kendo UI grid server filtering

I am trying to filter Kendo UI grid server side filter. The developer tools show this in query string
/Home/GetUsmMessage?{"filter":{"logic":"and","filters" [{"field":"MessageId","operator":"eq","value":1}]},"group":[]} GET 200 application/json
I created a object structure so that I read the structure to object
public ActionResult GetUsmMessage(FilterContainer filter)
{
//Code to read the filter container
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Object structure for filter container:
public class FilterContainer
{
public List<FilterDescription> filters { get; set; }
public string logic { get; set; }
}
public class FilterDescription
{
public string #operator { get; set; }
public string field { get; set; }
public string value { get; set; }
public List<FilterDescription> filters { get; set; }
public string logic { get; set; }
}
It still gives me a null object when I debug controller function. Please help
Got the answer...I forgot to add type of request as Http post ....
In case of WebApi controller, you could use [FromUri] attributes and GET verb:
public HttpResponseMessage Get(
[FromUri]IEnumerable<SortParameter> sort,
[FromUri]FilterContainer filter,
int take = 10, int skip = 0)

EF Code First, create new object in collection with a proxy

How can I create+persist+have-a-proxy-to a new instance of a code-first poco using only navigation property collections? In the bellow code, I show how you might want to do this, if using member functions to create POCOs that then create POCOs. You don't have a DbContext, but if you create an object and persist it using DbSet.Add, the returned object isn't a proxy, so you can't in turn use its DbSet.Add to add a different sub-object.
In this code, if you call MailingList.AddIncomingMessage("my message"), you get an exception at the "OOPS" comment, because the created msg isn't a proxy and thus its Message.doodads property is null.
class Doodad {
public int ID { get; set; }
public string doodad { get; set; };
}
class Message {
public int ID { get; set; }
public virtual MailingList mailingList { get; set; }
public virtual ICollection<Doodad> doodads { get; set; }
public string text { get; set; }
public void GetDoodadCreateIfNeeded(string doodad) {
try {
// won't be found since we just created this Message
return this.doodads.First(d => d.doodad == doodad);
} catch (Exception e) {
Doodad newDoodad = new Doodad() { doodad=doodad };
// OOPS! this.doodads == null, because its not a proxy object
this.doodads.Add(newDoodad);
return newDoodad;
}
}
}
class MailingList {
public int ID { get; set; }
public virtual ICollection<Message> messages { get; set; }
public void AddIncomingMessage(string message) {
var msg = new Message() { text=message };
// we have no Context, because we're in a POCO's member function
this.messages.Add(msg);
var doodad = msg.GetDoodadCreateIfNeeded("bongo drums");
}
}
EDIT: sorry guys, I forgot to put the property accessors and ID in for this simplified case, but I am using them in the actual code.
It has nothing to do with proxies. It is the same as any other code - if you want to use object / collection you must first initialize it! Your fist command:
return this.doodads.First(d => d.doodad == doodad);
doesn't throw exception because it didn't find doodad but because the doodads is null.
What do you need to do? You need to initialize collections before you first use them. You can do it:
Directly in their definition
In entity's constructor
In property getter (lazy initialization) once they are first needed - that would require to change your fields to properties which is btw. correct way to write classes in .NET
In your custom methods you can check if they are null and initialize them
Complementary to the navigation property, you need to have a property that is the Id of the foreign key.
So your MailingList will need to have this property:
[Key] // this attribute is important
public int Id { get; set; }
and you'll have to change the Message classe to have these properties:
public virtual int mailingListId { get; set;
public virtual MailingList mailingList { get; set; }
The { get; set; } property is important, so that it is a property, not just a public attribute.