I have below class with Header and Child class. I would like to know how to serialize child object using newtonsoft.I have tried below child object, but its return only one record where as child object contain 4 record
public class StyleBomLeatherSetupHeader
{
public int StyleStockID { get; set; }
public List<StyleBomLeatherSetup> Details { get; set; }
}
public class StyleBomLeatherSetup
{
public int StyleBomLeatherID { get; set; }
public int StyleStockID { get; set; }
public int? TypeID { get; set; }
public int? PartNoID { get; set; }
public int? ComponentID { get; set; }
public int? LeatherID { get; set; }
public int? ColorID { get; set; }
public decimal? Norms { get; set; }
public decimal? Wastage { get; set; }
public decimal? TotalNorms { get; set; }
}
Serialize json object:-
styleBomLeatherSetupHeader.StyleStockID = styleStockSetup.StyleStockID;
styleBomLeatherSetupHeader.Details = styleBomLeatherSetups;
protected StyleBomLeatherSetupHeader styleBomLeatherSetupHeader { get; set; } = new StyleBomLeatherSetupHeader();
string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);
After you have the header object setup, you can point to the child list with your property "Details". And with that been said, you can serialize just that property, like this:
string detailsJson =JsonConvert.SerializeObject(styleBomLeatherSetupHeader.Details);
public class StyleBomLeatherSetupHeader
{
public StyleBomLeatherSetupHeader ()
{
Details = new List<StyleBomLeatherSetup>();
}
public int StyleStockID { get; set; }
public IList<StyleBomLeatherSetup> Details { get; set; }
}
public class StyleBomLeatherSetup
{
public int StyleBomLeatherID { get; set; }
public int StyleStockID { get; set; }
public int? TypeID { get; set; }
public int? PartNoID { get; set; }
public int? ComponentID { get; set; }
public int? LeatherID { get; set; }
public int? ColorID { get; set; }
public decimal? Norms { get; set; }
public decimal? Wastage { get; set; }
public decimal? TotalNorms { get; set; }
}
Then
styleBomLeatherSetupHeader.StyleStockID=styleStockSetup.StyleStockID;
foreach(styleBomLeatherSetup in styleBomLeatherSetups)
{
styleBomLeatherSetupHeader.Details.Add(new StyleBomLeatherSetup{
// map your properties.
});
}
string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);
I have a Json model that looks like this
private class SearchMetadataJson
{
public string entertain { get; set; }
public string master { get; set; }
public string memail { get; set; }
public string key { get; set; }
public (int, string)[] mood { get; set; }
public int? soundnumber { get; set; }
public int? ftv { get; set; }
public int? com { get; set; }
public (int, string)[] sims { get; set; }
public (int, string)[] keysecond { get; set; }
public string popt { get; set; }
public (string, string) syncs { get; set; }
}
And I try to de-serialize the object like this
var CommentObj = JsonSerializer.Deserialize<SearchMetadataJson>(CommentAsString);
The data that I'm trying to de-serialize (aka "CommentAsString") looks like this
"{\"entertain\":\"PEG\",\"master\":\"Phos Ent Group\",\"memail\":\"example#example.com\",\"key\":\"Db\",\"mood\":{\"1\":\"TypeA\",\"4\":\"TypeB\",\"5\":\"TypeC\"},\"soundnumber\":\"5\",\"ftv\":\"4\",\"com\":\"3\",\"sims\":{\"1\":\"Band1\",\"2\":\"Band2\"},\"keysecond\":{\"1\":\"KeyWord1\",\"2\":\"KeyWord2\",\"3\":\"KeyWord3\"},\"syncs\":{\"Other pubber\":\"example2#example.com\"}}"
But I keep getting this error
Does anyone see what the problem is?
Update
The integers in CommentAsString are variables and will be different every time the function is called so I can't make a Json Object that has a key value of a particular integer.
Let's look at the actual formatted data structure
{
"entertain":"PEG",
"master":"Phos Ent Group",
"memail":"example#example.com",
"key":"Db",
"mood":{
"1":"TypeA",
"4":"TypeB",
"5":"TypeC"
},
"soundnumber":"5",
"ftv":"4",
"com":"3",
"sims":{
"1":"Band1",
"2":"Band2"
},
"keysecond":{
"1":"KeyWord1",
"2":"KeyWord2",
"3":"KeyWord3"
},
"syncs":{
"Other pubber":"example2#example.com"
}
}
Converting these to an array of tuple would be unusual. What you seemingly have are dictionary's
Example
private class SearchMetadataJson
{
public string entertain { get; set; }
public string master { get; set; }
public string memail { get; set; }
public string key { get; set; }
public Dictionary<int,string> mood { get; set; }
public int? soundnumber { get; set; }
public int? ftv { get; set; }
public int? com { get; set; }
public Dictionary<int,string> sims { get; set; }
public Dictionary<int,string> keysecond { get; set; }
public string popt { get; set; }
// public (string, string) syncs { get; set; }
}
It's debatable whether the last property is an object or another dictionary as well.
"syncs":{
"Other pubber":"example2#example.com"
}
However, I'll leave that up to you.
your have error in the model, use this site for convert your json in c#
https://json2csharp.com/
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Mood {
public string _1 { get; set; }
public string _4 { get; set; }
public string _5 { get; set; }
}
public class Sims {
public string _1 { get; set; }
public string _2 { get; set; }
}
public class Keysecond {
public string _1 { get; set; }
public string _2 { get; set; }
public string _3 { get; set; }
}
public class Syncs {
public string Otherpubber { get; set; }
}
public class Root {
public string entertain { get; set; }
public string master { get; set; }
public string memail { get; set; }
public string key { get; set; }
public Mood mood { get; set; }
public string soundnumber { get; set; }
public string ftv { get; set; }
public string com { get; set; }
public Sims sims { get; set; }
public Keysecond keysecond { get; set; }
public Syncs syncs { get; set; }
}
try again with using this
first read your string
this is the response using post, get or delete
var response = await client.PostAsync("your-url", datasBody);
var contentData = await response.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
var CommentObj = JsonSerializer.Deserialize<Root>(contentData, options);
if your model is bad or not match using
[JsonProperty("entertain")]
public string entertain { get; set; }
You will either need to use a custom converter or convert your tuples into separate classes with fields to explain what each field is used for.
This question already has answers here:
convert a list of objects from one type to another using lambda expression
(14 answers)
How to cast one compound custom type to another
(2 answers)
C# "cannot implicitly convert type" same model properties
(4 answers)
Closed 2 years ago.
Based on the module name I want to return different lists of different types but problem is that I cannot change the return type for each so I wrote a generic class that has the same properties but it doesn't work that way. How to achieve it.
public List<Models.TasksList> Get(string module)
{
//var query= "";
using (var context = new TasksPlanEntities())
{
if (module == "PEMS")
{
var query = from st in context.PIRTaskLists
select st;
return query.ToList<Models.TasksList>();
else if (module == "PSVMS")
{
var query = from st in context.PSVMS_EnggData
select st;
return query.ToList<Models.TasksList>();
}
}}
TasksList
public class TasksList
{
public int OperationID { get; set; }
public string PIRCode { get; set; }
public string TaskName { get; set; }
public string OperationNo { get; set; }
public string OperationCode { get; set; }
public string OperationDescription { get; set; }
//public static explicit operator TasksList(ObjectResult<GetTaskPlans_EPICOR_Result> v)
//{
// throw new NotImplementedException();
//}
public string Resource { get; set; }
public string NDTResources { get; set; }
public float Duration { get; set; }
public string RequiredEquipmentStatus { get; set; }
public string TimeBaseInterval { get; set; }
public DateTime StartDate { get; set; }
public DateTime LastInspDate { get; set; }
public DateTime NextInspDate { get; set; }
public string FunctionalLocation { get; set; }
}
throws error
Cannot implicitly convert to system.collection.generic.list<Models.TasksList>
Even though the TasksList class has exactly the same names and all. I tried everything but doesn't work out. Why it is so?
Why this is happening since it's the same structure.
Update:
public virtual DbSet<PIRTaskList> PIRTaskLists { get; set; }
public partial class PIRTaskList
{
public int OperationID { get; set; }
public string PIRCode { get; set; }
public string TaskName { get; set; }
public Nullable<int> OperationNo { get; set; }
public Nullable<int> Counter { get; set; }
public string OperationCode { get; set; }
public string OperationDescription { get; set; }
public string Resource { get; set; }
public string NDTResources { get; set; }
public Nullable<double> Duration { get; set; }
public string RequiredEquipmentStatus { get; set; }
public string TimeBaseInterval { get; set; }
public string InspectionType { get; set; }
public string TimeBaseInterval_UOME { get; set; }
public string Description { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> LastInspDate { get; set; }
public string Remarks { get; set; }
public Nullable<System.DateTime> NextInspDate { get; set; }
public Nullable<System.DateTime> IntermediateDue { get; set; }
public Nullable<System.DateTime> ThroughDue { get; set; }
public string DueDate { get; set; }
public string GroupStatusID { get; set; }
public Nullable<int> StatusID { get; set; }
public Nullable<int> EnggDataID { get; set; }
public string FunctionalLocation { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
public Nullable<int> CreatedBy { get; set; }
public Nullable<System.DateTime> ModifiedOn { get; set; }
public Nullable<int> ModifiedBy { get; set; }
public string PersonName { get; set; }
public string CostPerHour_Dollar { get; set; }
}
This is very simple, there's nothing that allows a list of PIRTaskList to be implicitly converted into a list of TasksList. The fact that the classes share the same properties names is irrelevant.
You have many options and which one you choose depends entirely on your project/team and knowledge you have about the system that we don't.
Use query.Select(x => new TasksList ...).ToList() to manually transform the items
Use an implicit/explicit conversion with a .Select
Use a library like AutoMapper
Use a List<dynamic>/List<object> (and lose type safety)
Probably more options that I cannot think of right now
In my webapi2 application I used db first generation and I created a partial class of context to set both ProxyCreationEnabledand LazyLoadingEnabled to false.
But when I use db.ExameViaAereaOssea.Where(e => e.ConsultaId == model.ConsultaId).ToList() the relation property Consulta is loaded too.
That not happing when I use db.ExameViaAereaOssea.AsNoTracking().Where(e => e.ConsultaId == consultaId).ToList()
I don't want use AsNoTracking for every query
Here are my two classes
public partial class ExameViaAereaOssea
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ExameViaAereaOssea()
{
}
public int ExameViaAereaOsseaId { get; set; }
public Nullable<int> ConsultaId { get; set; }
public string VAOE125 { get; set; }
public string VAOE250 { get; set; }
public string VAOE500 { get; set; }
public string VAOE750 { get; set; }
public string VAOE1000 { get; set; }
public string VAOE1500 { get; set; }
public string VAOE2000 { get; set; }
public string VAOE3000 { get; set; }
public string VAOE4000 { get; set; }
public string VAOE6000 { get; set; }
public string VAOE8000 { get; set; }
public string VOOE500 { get; set; }
public string VOOE750 { get; set; }
public string VOOE1000 { get; set; }
public string VOOE2000 { get; set; }
public string VOOE3000 { get; set; }
public string VOOE4000 { get; set; }
public string TipoAudiometria { get; set; }
public virtual Consulta Consulta { get; set; }
}
public partial class Consulta
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Consulta()
{
this.ExameViaAereaOssea = new HashSet<ExameViaAereaOssea>();
}
public int ConsultaId { get; set; }
public DateTime? Data {get;set;}
public Nullable<int> PacienteId { get; set; }
public Nullable<int> TipoConsultaId { get; set; }
public Nullable<int> PacienteDadosProfissionaisId { get; set; }
public Nullable<int> ClienteId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ExameViaAereaOssea> ExameViaAereaOssea { get; set; }
}
And here is the usage.
public class RegraConsulta(){
public ExamesConsulta BuscaExamesConsulta(Consulta model) {
using (var db = new winmedEntities(false))
{
var retorno = new ExamesConsulta();
retorno.DataConsulta = RetornaDataConsulta(db, model.ConsultaId);
retorno.exAereaOssea = db.ExameViaAereaOssea.Where(c => c.ConsultaId == model.ConsultaId).ToList();
return retorno;
}
}
public DateTime RetornaDataConsulta(winmedEntities db, int consultaId)
{
var consulta = db.Consulta.Find(consultaId);
if (consulta == null)
throw new RegraNegocioException("Consulta não encontrada");
return consulta.Data.Value;
}
}
The return is used in Web Api Controller and return method used like return Ok(new RegraConsulta().BuscaExamesConsulta(new Consulta { ConsultaId = 1 }));
I have the following method which is used to retrieve all values as strings from an object using reflection. The object can have IEnumerables within them and I also want to retrieve these values. A list of ignore fields also needs to be taken into account so that those field's values are not returned.
public static IEnumerable<string> StringContent(this object obj, IEnumerable<string> ignoreProperties = null)
{
Type t = obj.GetType();
foreach (var prop in t.GetProperties())
{
if (ignoreProperties != null && ignoreProperties.Contains(field.Name))
{
continue;
}
var value = prop.GetValue(obj);
if (value != null)
{
if (value is IEnumerable<object>)
{
foreach (var item in (IEnumerable<object>)value)
{
foreach (var subValue in item.StringContent())
{
yield return subValue.ToString();
}
}
}
else
{
yield return value.ToString();
}
}
}
}
This method does work perfectly and gives me the correct result. However, I need to speed it up as much as possible because this is performed a lot of times.
Does anybody have any suggestions?
Thanks in advance!
** EDIT **
Example Test Case:
[TestMethod]
public void StringContent()
{
Project project = projectA;
List<string> ignoreFields = new List<string>() { "SalesEngineer", "CreationDate" };
var result = project.StringContent(ignoreFields);
Assert.IsTrue(result.Count() == 26);
}
Project Object:
public class Project : IEntity
{
public Project()
{
Products = new List<ProjectProducts>();
}
public int Id { get; set; }
public DateTime CreationDate { get; set; }
public string SalesEngineer { get; set; }
public string SalesEngineerEmail { get; set; }
public int? TeamId { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Originator { get; set; }
public string ContactName { get; set; }
public string MainClient { get; set; }
public string Contractor { get; set; }
public string ContractorContactName { get; set; }
public string ContractorLocation { get; set; }
public string Wholesaler { get; set; }
public string WholesalerContactName { get; set; }
public string WholesalerLocation { get; set; }
public float EstimatedValue { get; set; }
public float CalculatedValue {
get { return EstimatedValue/Convert.ToSingle(Currency != null ? Currency.Rate : (decimal)1.0); }
}
public int Probability { get; set; }
public int SectorId { get; set; }
public int TypeId { get; set; }
public string StatusCode { get; set; }
public string LostTo { get; set; }
public int ReasonId { get; set; }
public string SecondaryEngineer { get; set; }
public float SplitPercentage { get; set; }
public DateTime ExpectedOrder { get; set; }
public DateTime? RequiredOnSiteBy { get; set; }
public bool LightingDesignRequired { get; set; }
public string ReasonForLightingDesign { get; set; }
public DateTime? DesignRequiredBy { get; set; }
public DateTime? FollowUp { get; set; }
public string Comments { get; set; }
public int CurrencyId { get; set; }
public bool Void { get; set; }
public string AttachmentFolder { get; set; }
public virtual Currency Currency { get; set; }
public virtual Reason Reason { get; set; }
public virtual ProjectStatus Status { get; set; }
public virtual ProjectType Type { get; set; }
public virtual Sector Sector { get; set; }
public virtual ICollection<ProjectProducts> Products { get; set; }
public virtual Team Team { get; set; }
public object Key
{
get { return Id; }
}
}
You can use stringify package.
It exists in Nuget.
You can Hide parameters with Hidden attribute.
You can print every object with a.stringify();