Statut 400 : The JSON value could not be converted to AppTest.Shared.Models.Developer

sblb 1,231 Reputation points
2022-11-27T16:02:04.083+00:00

Hi,

I've application where I try to make one-to-many relationship. the controller was created (see the post here : ef-one-to-many-to-assure-the-link-with-the-main-ta.html)
I've the DeveloperActionsController that I tested with swagger. So I received the error message.
Have you an idea how I can fix this error?

{  
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",  
  "title": "One or more validation errors occurred.",  
  "status": 400,  
  "traceId": "00-938ace42dd83c35b05f556b91c0a3170-c2901182370015ff-00",  
  "errors": {  
    "developer": [  
      "The developer field is required."  
    ],  
    "$.actionItems[0].developer": [  
      "The JSON value could not be converted to AppTest.Shared.Models.Developer. Path: $.actionItemsTest[0].developer | LineNumber: 12 | BytePositionInLine: 31."  
    ]  
  }  
}  

Class model :

 public partial class Developer  
    {  
        [Key]  
        public int DeveloperId { get; set; }  
        public List<ActionItem>? ActionItems{ get; set; }  
    }  
  
    public class ActionItem  
    {  
        [Key]  
        public int ActionItemId { get; set; }  
        public string? Tilte { get; set; }  
        public string? Description { get; set; }  
        public string? State { get; set; }  
        public DateTime? OpenDate { get; set; }  
        public DateTime? PlanDate { get; set; }  
        public DateTime? CloseDate { get; set; }  
  
        public int DeveloperId { get; set; }  
        public Developer? Developer { get; set; }  
    }  

Controller

[Route("api/[controller]")]
[ApiController]
public class DeveloperActionsController : ControllerBase
{
private readonly ApplicationDBContext _contexts;

    public DeveloperActionsController(ApplicationDBContext contexts)  
    {  
        this._contexts= contexts;  
    }  

    // GET: api/<DeveloperActionController>  
    [HttpGet]  
    public IEnumerable<Developert> GetDevelopersWithActions()  
    {  
        return _contexts.DeveloperTests.Include(a => a.ActionItems).ToList();  
    }  

    // GET api/<DeveloperActionController>/5  
    [HttpGet("{id}")]  
    public async Task<ActionResult<Developer>> GetDeveloperActions(int id)  
    {  
        DeveloperTest? developer = await _contexts.Developer  
            .Include(a => a.ActionItems)  
            .FirstOrDefaultAsync(d => d.DeveloperId == id);  

        if (developer == null)  
        {  
            return NotFound();  
        }  

        return Ok(developer);  
    }  

    // POST api/<DeveloperActionController>  
    [HttpPost]  
    public async Task<ActionResult<Developer>> PostAsync([FromBody] Developer developer)  
    {  
        _contexts.Developer.Add(developer);  
        await _contexts.SaveChangesAsync();  

        return CreatedAtAction(nameof(GetDeveloperActions), new { id = developer.DeveloperId }, developer);  
    }  

    // PUT api/<DeveloperActionController>/5  
    [HttpPut("{id}")]  
    public async Task<ActionResult<Developer>> Put(int id, [FromBody] ActionItem actionItem)  
    {  
        DeveloperTest? developer = await _contexts.Developer  
            .Include(a => a.ActionItems)  
            .FirstOrDefaultAsync(d => d.DeveloperId == id);  

        if (developer == null)  
        {  
            return NotFound();  
        }  

        developer.ActionItems.Add(actionItem);  
        await _contexts.SaveChangesAsync();  

        return CreatedAtAction(nameof(GetDeveloperActions), new { id = developer.DeveloperId }, developer);  

    }  

    // DELETE api/<DeveloperActionController>/5  
    [HttpDelete("{id}")]  
    public async Task<IActionResult> Delete(int id)  
    {  
        DeveloperTest? developer = await _contexts.Developer  
            .Include(a => a.ActionItems)  
            .FirstOrDefaultAsync(d => d.DeveloperId == id);  

        if (developer == null)  
        {  
            return NotFound();  
        }  

        _contexts.Remove(developer);  

        await _contexts.SaveChangesAsync();  

        return NoContent();  
    }  

}  
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,665 questions
{count} votes

5 answers

Sort by: Most helpful
  1. sblb 1,231 Reputation points
    2022-11-29T20:16:10.767+00:00

    Hi, sorry for the late answer.

    could you please tell us when you get this error? On loading or while sending any request?

    I received this error message when I try to test POST method via swagger

    265424-image.png

    265403-image.png


  2. sblb 1,231 Reputation points
    2022-11-30T20:20:19.003+00:00

    My application is relatively heavy for testing.
    So I redid a test application and I have exactly what you suggested to put a foreign key.
    The controller, modelclass and ApplicationDBcontext are what I have at the beginning of this post. I also did a migration to get access to the Developers & ActionItems tables.

    I added a razor page to initialize the Developers table first. Nothing happens when I do htpp request.
    Plus When I added the simple for loop I the error.

    Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]  
          Unhandled exception rendering component: Object reference not set to an instance of an object.  
    System.NullReferenceException: Object reference not set to an instance of an object.  
    

    Anyway when I use swagger and test Get, Post, Put, Delete I receive the status 404!!

    I would really like to understand why I get this type of error when I am doing something that is actually quite simple.

    @page "/test"  
    @using AppTest.Shared.Models  
    @using System.Text.Json  
    @using System.ComponentModel  
    @inject HttpClient Http  
      
    <h3>TestDev</h3>  
          
    <table class="table">  
            <thead>  
                <tr>  
                    <th>ID</th>                                       
                </tr>  
            </thead>  
            <tbody>       
          @foreach (var dev in developer)  
            {  
                <tr>  
                    <td>@dev.DeveloperId</td>                      
                </tr>  
            }           
            </tbody>  
      </table>  
      <table class="table">  
            <thead>  
                <tr>  
                    <th>ID</th>  
                    <th>State</th>                  
                </tr>  
            </thead>  
            <tbody>                
            </tbody>  
      </table>  
      
    @code{  
        Developer[]? developer { get; set; }  
             
        protected override async Task OnInitializedAsync()  
        {  
            developer=await Http.GetFromJsonAsync<Developer[]>("api/developeractions");  
        }  
     }  
    
    0 comments No comments

  3. Bruce (SqlWork.com) 73,101 Reputation points
    2022-11-30T21:57:36.473+00:00

    your issues are from using entity models as api models. in the ActionItem you are trying to post navigation values. create separate POCO request/response models for the json.


  4. sblb 1,231 Reputation points
    2022-12-06T12:58:29.217+00:00

    Hi,
    I tried it in controller :

     return Ok(JsonSerializer.Serialize(developer, new JsonSerializerOptions  
                {  
                    PropertyNamingPolicy = null  
                }));  
    

    your issues are from using entity models as api models

    Could you explain because I don't really understand? thanks in advance

    0 comments No comments

  5. sblb 1,231 Reputation points
    2022-12-06T21:14:56.757+00:00

    I have searched the internet and I can't find (or don't quite understand the principle) a clear explanation for creating separate POCO request/response models for the json.

    Could you please help me to unblock?

    thanks in advance !!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.