【问题标题】:How to deserialize a JSON object?如何反序列化 JSON 对象?
【发布时间】:2019-03-04 05:08:57
【问题描述】:

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

`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 core下面的方法

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

【问题讨论】:

  • 我可能错了,但看起来您的 JSON 对象与模型不匹配

标签: c# asp.net json angular angular7


【解决方案1】:

您的属性前有下划线,这就是 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&lt;Candidate_Educational_Info_Table&gt;

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" });
}

【讨论】:

  • 这个 json 字符串和测试来自哪里??
  • @HasnatAdil 我对其进行了编辑以使其适用于您当前的方法。
  • var fooObjectArray= test.First;这个 test.first 给出错误
  • @HasnatAdil 修改错字
  • @HasnatAdil 如果您的问题得到解答,请将其标记为已回答。谢谢
【解决方案2】:

有多种 JSON 序列化程序。我常用的是Newtonsoft Json

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

您还可以使用动态反序列化,它可以在没有类定义的情况下进行反序列化。您可以使用System.Web.Script.Serialization 解析并获取动态对象。它还需要System.Web.Extensions 参考

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

【讨论】:

  • 如何传递 System.Web.Extensions 引用?
  • 当我通过 newtonsoft JSON 对其进行反序列化时,会出现错误 cannot convert newtonsoft.json.linq.jobject to string
【解决方案3】:
 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;
    }
    }
    }

【讨论】:

  • saveUser(data: User) { console.log(data); this._userService.SaveUser('localhost:58649/api/Users/PostUser' , data) .subscribe(); this.ifinserted = true;警报(“插入”); }
  • ngOnDestroy() { this.subscriptions.forEach(s => s.unsubscribe()); }
【解决方案4】:
   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()
    }
    });
   }
   }

【讨论】:

  • 请为您的解决方案写一个解释。
【解决方案5】:
 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());
   }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    相关资源
    最近更新 更多