简体   繁体   English

如何反序列化JSON对象?

[英]How to deserialize a JSON object?

I am working on Website in which front end is developed in Angular 7 . 我正在使用在Angular 7中开发前端的网站上工作。 I am sending an array from angular in json format to c# asp.net core. 我正在将数组从json格式的angular发送到c#asp.net core。 I am getting data in below format 我正在获取以下格式的数据

`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"
 }
]
}`

My Method in asp.net core below 我在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" });
    }

My code is not deserializing json object Any solution please as now I have spend one week in this problem. 我的代码未将反序列化json对象反序列化。请采用任何解决方案,因为我已经在此问题上花费了一周的时间。 My c# model is given below 我的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;
    }

There are a variety of JSON serializers. 有多种JSON序列化器。 The one i usually use is Newtonsoft Json 我通常使用的是Newtonsoft Json

Movie m = JsonConvert.DeserializeObject<Movie>(json);

You can also use dynamic deserilaization, which can deserialise without a class definition. 您还可以使用动态反序列化,而无需类定义就可以反序列化。 You can use System.Web.Script.Serialization to parse and get a dynamic object. 您可以使用System.Web.Script.Serialization解析并获取动态对象。 It also requires System.Web.Extensions reference 它还需要System.Web.Extensions参考

JavaScriptSerializer js = new JavaScriptSerializer();
dynamic modelItems = js.Deserialize<dynamic>(json);

You have underscores before your properties thats why the JsonConvert cannot map properly. 在属性之前有下划线,这就是JsonConvert无法正确映射的原因。

You can use [JsonProperty("")] attributes to map to the correct property 您可以使用[JsonProperty(“”)]属性映射到正确的属性

your properties would look like then 您的属性看起来像

[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; }

To handle for the rest. 处理其余的。 You have a root object called model. 您有一个称为模型的根对象。 But all we want is the List<Candidate_Educational_Info_Table> 但是我们只需要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" });
}
 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;
    }
    }
    }
   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()
    }
    });
   }
   }
 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());
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM