如何反序列化JSON对象?

时间:2019-03-04 05:08:58

标签: c# asp.net json angular angular7

我正在使用Angular 7开发前端的网站。我正在将数组从json格式的angular发送到c#asp.net core。我正在获取以下格式的数据

`First = {"model": [{
   "_organization_Name": "erw",
   "_designation": "dfs",
   "_p_Start_Date": "2019-02-28T19:00:00Z",
   "_p_End_Date": "2019-03-27T19:00:00Z"
 },
 {
   "_organization_Name": "erwfg",
   "_designation": "dfsfgfg",
   "_p_Start_Date": "2019-02-28T19:00:00Z",
   "_p_End_Date": "2019-03-27T19:00:00Z"
 }
]
}`

我在asp.net核心下面的方法

[HttpPost("[action]")]
    public IActionResult SaveProfessional([FromBody]JObject prof)
    {

        var obj = new Candidate_Professional_Info_Table(_context);
        obj.Identity_Number = 112131.ToString();
        obj = 
JsonConvert.DeserializeObject<Candidate_Educational_Info_Table>(prof);

        var result = obj.SaveProfessional(prof);
        return Ok(new { suces = "result" });
    }

我的代码未反序列化json对象请执行任何解决方案,因为我已经在此问题上花费了一周的时间。我的C#模型在下面给出

 public int ID { get; set; }
    public string Identity_Number { get; set; }
    [Required]
    [RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Organization Name Not Valid")]
    public string Organization_Name { get; set; }

    [Required]
    [RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
    public DateTime? p_Start_Date { get; set; }

    [RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
    public DateTime? p_End_Date { get; set; }
    [Required]
    [RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Designation Name Not Valid")]
    public string Designation { get; set; }

    public  bool InProgress { get; set; }
    [NotMapped]
    public List<Candidate_Professional_Info_Table> listprof { get; set; }
    [NotMapped]
    private readonly RegConnString _Context;
    public Candidate_Professional_Info_Table(RegConnString connString)
    {
        _Context = connString;
    }

5 个答案:

答案 0 :(得分:0)

有各种各样的JSON序列化器。我通常使用的是Newtonsoft Json

 "setupFiles": ["<rootDir>/setup.js"]

您还可以使用动态反序列化,该动态反序列化无需类定义即可反序列化。您可以使用Movie m = JsonConvert.DeserializeObject<Movie>(json); 进行解析并获取动态对象。它还需要System.Web.Script.Serialization参考

System.Web.Extensions

答案 1 :(得分:0)

在属性之前有下划线,这就是JsonConvert无法正确映射的原因。

您可以使用[JsonProperty(“”)]属性映射到正确的属性

您的属性会像这样

[Required]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Organization Name Not Valid")]
[JsonProperty("_organization_Name")]
public string Organization_Name { get; set; }

[Required]
[RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
[JsonProperty("_p_Start_Date")]
public DateTime? p_Start_Date { get; set; }

[RegularExpression("^/d{1, 2}///d{1,2}///d{4}$")]
[JsonProperty("_p_End_Date")]
public DateTime? p_End_Date { get; set; }

[Required]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Designation Name Not Valid")]     
[JsonProperty("_designation")]
public string Designation { get; set; }

处理其余部分。您有一个称为模型的根对象。但是我们只需要List<Candidate_Educational_Info_Table>

public IActionResult SaveProfessional([FromBody]JObject prof)
{
   //select the model itself. Also do some nullchecking to prevent errors if empty
   var fooModel = prof.First;
   //select the content of the model(your actual array). Also do some nullchecking to prevent errors if empty
   var fooObjectArray= fooModel.First;
   var theDeserializedList = fooObjectArray.ToObject<List<Candidate_Educational_Info_Table>>();

   foreach (var item in theDeserializedList)
   {
      //handle the rest of what you want to do. 
      //As i see you inject the context into the objects on create but this will not be possible if you use the deserialze. 
      //Its better to pass the context on the method SaveProfessional
   }

    return Ok(new { suces = "result" });
}

答案 2 :(得分:0)

 var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
        config.EnableCors(cors);


.Linq;

namespace MTBCTest.Controllers
{
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class UsersController : ApiController
{
    private testingDbEntities db = new testingDbEntities();

    // GET: api/Users
    [HttpGet]
    public IQueryable<User> GetUsers()
    {
        return db.Users;
    }

    // GET: api/Users/5
    [ResponseType(typeof(User))]
    [HttpGet]
    public IHttpActionResult GetUser(int id)
    {
        User user = db.Users.Find(id);
        if (user == null)
        {
            return NotFound();
        }

        return Ok(user);
     }

    // PUT: api/Users/5
    [ResponseType(typeof(void))]
    [HttpPost]
    public IHttpActionResult PutUser(User user)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        User ob = db.Users.Find(user.ID);
        ob.FirstName = user.FirstName;
        ob.LastName = user.LastName;
        ob.Password = user.Password;
        ob.EmailID = user.EmailID;
        db.Entry(ob).State = EntityState.Modified;
        db.SaveChanges();
        return Ok();

     }

    // POST: api/Users
     [HttpPost]
     public IHttpActionResult PostUser(User user)
     {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.InserUser(user.FirstName,user.LastName,user.EmailID, user.Password);
        db.SaveChanges();



        return Ok();
    }

    // DELETE: api/Users/5
    [HttpGet]
    public IHttpActionResult DeleteUser(int id)
    {
        User user = db.Users.Find(id);
        if (user == null)
        {
            return NotFound();
        }

        db.Users.Remove(user);
        db.SaveChanges();

        return Ok();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool UserExists(int id)
    {
        return db.Users.Count(e => e.ID == id) > 0;
    }
    }
    }

答案 3 :(得分:0)

   export class User {
   public FirstName: string;
  public LastName: string;
  public EmailID: string;
  public Password: string;
    }
   import { Injectable } from '@angular/core';
   import { HttpClientModule, HttpClient, HttpHeaders } from '@angular/common/http';
   import {User} from '../user';
   import { Observable } from 'rxjs';
   import { convertActionBinding } from 
  '@angular/compiler/src/compiler_util/expression_converter';
  @Injectable({
  providedIn: 'root'
 })
  export class UserServiceService {

   // tslint:disable-next-line:variable-name
   constructor(private _http: HttpClient) {  }

  public SaveUser(api: string , userData: User): Observable<any> {
   // tslint:disable-next-line:no-trailing-whitespace
  return this._http.post<any>(api, userData, { 
   headers : new HttpHeaders({
   'Content-Type' : 'application/json'
    })
   });
   }
   public DeleteUser(api: string , id: number): Observable<any> {
     return this._http.get<any>(api , {
  //  headers : new HttpHeaders({
  //    'Content-Type' : 'application/x-www-form-urlencoded'
   //  }),
    params: {
     id: id.toString()
     }
    });
   }
    public editUserByID(api: string, userData: User): Observable<any> {
   return this._http.post<any>(api, userData , {
    // headers: new HttpHeaders({
    //   'Content-Type' : 'application/json'
    // })
    });
    }
   public GetUsers(api: string): Observable<User[]> {
  return this._http.get<User[]>(api);
   }
    public GetUsersByID(api: string , ID: number): Observable<User> {
   return this._http.get<User>(api, {
     // headers: new HttpHeaders({
    //   'Content-Type': 'application/x-www-form-urlencoded'
    // }),
      params: {
      ID: ID.toString()
    }
    });
   }
   }

答案 4 :(得分:0)

 import { Component, OnInit, OnDestroy } from '@angular/core';
 import {UserServiceService} from 'src/Models/Services/user-service.service';
 import { User } from 'src/Models/user';
 import { Subscription } from 'rxjs';

 @Component({
 selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
   export class UserComponent implements OnInit, OnDestroy {
  subscriptions: Subscription [] = [];
 userData: User;
   users: User[];
   ifinserted: boolean;
  isEdited: boolean;
  // tslint:disable-next-line:variable-name
   constructor(private _userService: UserServiceService) { }

  ngOnInit() {
   this.userData = new User();
   this.ifinserted = false;
   this.isEdited  = false;
   }
  saveUser(data: User) {
 console.log(data);
 this._userService.SaveUser('http://localhost:58649/api/Users/PostUser' , data)
 .subscribe();
 this.ifinserted = true;
    alert('Inserted');

   }
  getUser() {
  this._userService.GetUsers('http://localhost:58649/api/Users/GetUsers')
   .subscribe((data: User[]) => {
   this.users = data;
  });
   }
 editUser(i: number) {
  this.subscriptions.push(
   this._userService.GetUsersByID('http://localhost:58649/api/Users/GetUser' , i)
  .subscribe((data: User) => {
   this.userData = data;
  this.isEdited = true;
  }));
   }
  editUserByID(obj: User) {
  this._userService.editUserByID('http://localhost:58649/api/Users/PutUser' , obj)
 .subscribe();
 this.isEdited = false;
 alert('Edited');
  }
  deleteUser(i: number) {
   console.log(i);
   this._userService.DeleteUser('http://localhost:58649/api/Users/DeleteUser' , i)
  .subscribe();
   alert('Deleted');
    }
  ngOnDestroy() {
   this.subscriptions.forEach(s => s.unsubscribe());
   }
 }