JSON structure could not be converted to a nested structure in webAPi2 due to

Encountering an issue while attempting to call a web2.0 API.

Error Message: "Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'NG_API_DNET_FRX.Models.mproject'."

The JSON data sent from the webpage (which utilizes Angular) is as follows:

{
    "id": "3137",
    "clientId": "2",
    "Name": "MFAQ project1",
    "EstimatedStartDate": "07/01/2022",
    "EstimatedEndDate": "07/08/2022",
    "ActualStartDate": "07/15/2022",
    "ActualEndDate": "07/22/2022",
    "EstimatedBudget": "44444.0000",
    "ActualBudget": "55555.0000"
}

This is the representation of the JSON passed in, with double curly braces {{...}}:

{{
  "id": 3137,
  "clientId": 2,
  "Name": "MFAQ project1",
  "EstimatedStartDate": "07/13/2022",
  "EstimatedEndDate": "6/8/2022",
  "ActualStartDate": "6/15/2022",
  "ActualEndDate": "6/22/2022",
  "EstimatedBudget": 44444,
  "ActualBudget": 55555
}}

Describing the target structure:

public class mproject
{
    public int id;
    public int clientId;
    public string Name;
    public string EstimatedStartDate;
    public string EstimatedEndDate;
    public string ActualStartDate;
    public string ActualEndDate;
    public decimal EstimatedBudget;
    public decimal ActualBudget;
    public string sbProperties;
    public string projectType;

    public mprojectRev[] Revisions;
}


     [System.Web.Http.HttpPatch]
            [Route("{itemId_}")]
               public IHttpActionResult PatchItemById([FromUri] int itemId_, [FromBody] mproject webForm_  )
            {
                //if the parameter is of type mproject webform is null
   

//If i change the type to dynamic or object, and then try to //it, this is where i get the error
 
                //mproject webForm_;
                //try
                //{
                //    webForm_ = (mproject)webForm_1;
                //}
                //catch (Exception ex)
                //{
                //    return JSONStringResultExtension.JSONString(this, errorAsJSON(ex), HttpStatusCode.InternalServerError);
    
                //
    }
             }
     

No inner exception reported. The input does not include 3 properties defined on mproject, but I do not believe that to be the root cause, as it has worked before. Focusing on date-related issues for now.

In need of more insights on why the casting error persists rather than a direct solution. Seeking guidance on troubleshooting techniques.

Querying: What triggers this casting exception?

Interested in discovering resources offering detailed information about the casting error. Open to suggestions on effective troubleshooting approaches.

Answer №1

It appears that the JSON post is missing three key properties:

public string sbProperties;
public string projectType;

public mprojectRev[] Revisions;

If these properties are optional, consider updating them to be nullable:

public string? sbProperties ;
public string? projectType;

public mprojectRev[]? Revisions;

If these properties are required, make sure to include them in your request.

To troubleshoot further, you can open the developer tools by pressing F12 in your browser, navigate to the Network tab, click on the request, and select the response tab to view the full response from the API which may provide insights into the issues.

https://i.sstatic.net/gmcJC.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I specify a subset within an Angular FormGroup?

Let's consider a scenario: I have two forms, form1 and form2, each containing multiple FormControls. The common property among them is the FormControl with an id. Now, I need to pass these forms as arguments to a method that should only require know ...

Attach a click event to the button with a defined class using Angular

In order to meet the requirement, I need to track user click events on all buttons with a specific class. To do this, I have to bind the click event to all buttons and ensure that the same function is triggered in all components. Any ideas on how I can ac ...

Looking for a comprehensive index of bindable properties specifically for Angular HTTP elements?

MDN explains: To set default content for your <textarea>, you can place it between the opening and closing tags. However, <textarea> does not support the value attribute. In Angular property binding, we have the ability to bind to the value p ...

Navigating Assertions within Functional Code

When working with functional programming, I often encounter situations where my knowledge exceeds the type system of the language. Take for example this TypeScript scenario where I parse a UUID and display its embedded fields to the user. The program ini ...

Executing an API call in Angular using a for-loop

I'm working on a project where I need to make multiple API calls based on the length of a mockInput.json file. Here's how I have implemented it: api.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeade ...

Finding elements in an array based on a specific string contained within a property

I am currently working on filtering JSON data to specifically search for job roles that begin with a particular string. The structure of the JSON is as follows : "periods": [ { "periodName": "Week1", "teamName": "Tango", ...

Utilizing Rails to render a JSON partial within a model

In our application built on rails 3.2, we utilize the Jbuilder gem to generate json responses in a straightforward manner. A basic json view might look like this: _model_name.json.jbuilder json.extract!(page, :id, :name, :url_name) For more complex scen ...

Retrieving JSON data from embedded documents in Mongoid with Rails 4

I am looking to extract all embedded documents from a parent document and return them as a list of JSON elements. Here is an example of the document structure: class Parent include Mongoid::Document field :name, :type => String embeds_many :kids c ...

Show a mpld3 graph in an HTML page using the Django framework

Incorporating mpld3 to showcase matplotlib charts within an HTML page through django has been my recent focus. I utilize the mpld3.fig_to_dict method to convert a matplotlib figure into a JSON string and store it in a variable. However, I am encountering ...

Angular and Spring are producing a 415 Unsupported Media Type error

I have encountered a dilemma where I tried multiple solutions to no avail. The angular service code is as follows: app.factory('service',['$http','$q', function($http,$q){ return { get: function(m){ return $http.p ...

Problem encountered while generating a map using the map variances calculated by Guava

I am currently utilizing Google Guava for computing the variance between two maps. With these variances, my goal is to create another map for further processing in the following manner: Map<String, Map<String, Object>> fieldToDiffMap = new Ha ...

Is it really impossible to post complex JSON parameters with Restangular?

Is it possible to send a complex JSON object to a PUT route using Restangular? Restangular.one('model3ds', model.uuid).put( api_key: "blabla" model3d: { is_public: true } ) However, the data sent by Restangular appears as: ...

How can the panel within an accordion be enlarged or minimized?

Currently, I am implementing an accordion feature with the option to expand or collapse all panels using two buttons. My goal is to allow users to manage each panel within the accordion individually. However, I have encountered an issue that needs attenti ...

Looking for a way to toggle the visibility of a dropdown list when clicking on an input in Angular7?

My Angular7 application features a dropdown menu that automatically closes when an item is selected. Additionally, I have implemented functionality to toggle the dropdown open and closed by clicking on an input field. You can view a live example of this be ...

Simulation of documentElement language property in Jest

I am currently attempting to manipulate the documentElement lang property for my testing purposes, but I am struggling to find a solution. I have tried defining setupFiles in Jest config, which allowed me to define it but did not give me the option to chan ...

Having trouble with your JSONP callback not being received?

When attempting to make a JSONP request to yellowapi (Yellow Pages) and specifying a callback, I encountered an "invalid label" error. Below is the code I currently have: $.ajax({ dataType: 'jsonp', cache : false, url: "http://api.sandbox.yell ...

converting a string into json format using php

I need help with formatting the data retrieved from an API into key-value pairs for JavaScript. Currently, the data is in one big key and not properly formatted. How can I transform this data into key-value pairs? <?php header('Content-Type: ...

Using the Nodejs Array prototype filter method within a JSON object

Attempting to create a function that filters and returns specific strings within JSON data. Any advice is appreciated. Thank you! [ { line: '{"status":"waiting"}' } ] var body_W = []; body_W.push({line: JSON.stringif ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

Learn how to efficiently transfer row data or an array object to a component within Angular by utilizing the MatDialog feature

My goal is to create a functionality where clicking on a button within a specific row opens up a matDialog box displaying all the contents of that row. Below is the HTML snippet: <tr *ngFor="let u of users"> <td data-label="ID& ...