The JSON array is converted to a shared list, but not converted to a shared collection. What for?

I am sending Json Array from a client web application in asp.net webapi. For instance,

{ "SurveyId":3423, "CreatorId":4235, "GlobalAppId":34, "AssociateList":[ {"AssociateId":4234}, {"AssociateId":43}, {"AssociateId":23423}, {"AssociateId":432} ], "IsModelDirty":false, "SaveMode":null } 

Here, the Associated List is a JSON array. Usually it is automatically serialized to a List <> object.

Using the code below, I am posting a response to WebApi

 public IEnumerable<Associate> Post(ResponseStatus responseStatus) { return this.responsestatusrepository.ResponseStatusCheck(responseStatus); } 

The ResponseStatus class is shown below.

 public class ResponseStatus : AppBaseModel { public int SurveyId { get; set; } public int CreatorId { get; set; } public int GlobalAppId { get; set; } public List<Associate> AssociateList { get; set; } } 

I changed List <> to Collection <> as part of my code analysis correction. those. public Collection<Associate> AssociateList { get; set; }

But it always gets a null value when we use the collection instead of List. Is there any specific reason for this?

+6
source share
1 answer

Well, I think I will have to answer this indirectly. What you send to the server is an array of objects (in JSON format), but as soon as you start processing it in C #, the array of objects is now considered as a single C # object. Inside this object, your model expects one of the fields to be Collection of Associate.

That's right, when I work with JSON data similar to what was mentioned in this case, I prefer to use JOject Newtonsofts.

So, here is how I created a C # object with the JSON data you provided:

Your model is used:

 public class ResponseStatus { public int SurveyId { get; set; } public int CreatorId { get; set; } public int GlobalAppId { get; set; } public Collection<Associate> AssociateList { get; set; } } public class Associate { public int AssociateId { get; set; } } 

Made a routine that takes a string (JSON data) and returns an object of type ResponseStatus:

 using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; --------------------------------------------------------------------- public static ResponseStatus GetResponseStatusObject(string jsonData) { JObject jObject = JObject.Parse(jsonData); return jObject.ToObject<ResponseStatus>(); } 

Now, when I call this method and pass the same JSON data that you provided, I get the following:

Breakpoint after method ran

This may not solve your problem directly, but I hope it helps you in the right direction in understanding the serialization of an array / object when working with JavaScript / C #.

Good luck

0
source

Source: https://habr.com/ru/post/975650/


All Articles