Deserialize Objects with JsonConvert Class - c#

I have a weird issue and am confused.
I have 3 class:
public class ProductInfo
{
public List<PartInfo> PartInfos { get; set; }
public string Name { get; set; }
}
public class SubProductInfo : PartInfo
{
public ProductInfo ProductInfo { get; set; }
}
public class PartInfo
{
public string Name { get; set; }
public string Desc { get; set; }
}
I have some information for industrial products. each product has some part and some sub product. for each product I have an object from type 'ProductInfo'. for each part related to this product I have an object of type 'PartInfo' and for each sub product related to this product I have an object of type 'SubProductInfo'. this 'ProductInfo' object serialized with 'JsonConvert.SerializeObject' method.
Example for serialized information:
{"PartInfos":[{"Name":"Part1","Desc":"Part1's Desc"},{"ProductInfo":{"PartInfos":[{"Name":"SubProduct1's Part1","Desc":"SubProduct1's Part1 desc"},{"Name":"SubProduct1's Part2","Desc":"SubProduct1's Part2 desc"}],"Name":"SubProduct1"},"Name":"SubProduct1 Details","Desc":"SubProduct1's Desc"}],"Name":"Product1"}
now I want to deserialize these JSONs to orginal object. I used:
JsonConvert.DeserializeObject<ProductInfo>(serializedObject)
but in deserialization 'SubProductInfo' objects will deserialize to 'PartInfo' objects.
how I can deserialize these JSONs to Exactly orginal objects?

Check out this: https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm
When you're serializing, the protocol you're using usually has manners to solve problems like this, usually by type hinting. Basically your serialized product contains data that tells the deserializre which type to use when deserializing.

Like I commented, I really don't undestand what you are trying to achieve.
I think you want to make a list of SubProductInfo instead of PartInfo, as PartInfo is the base of SubProductInfo. Like this:
public class ProductInfo
{
public List<SubProductInfo> PartInfos { get; set; }
public string Name { get; set; }
}
public class SubProductInfo : PartInfo
{
public ProductInfo ProductInfo { get; set; }
}
public class PartInfo
{
public string Name { get; set; }
public string Desc { get; set; }
}
If a SubProductInfo is something different than a PartInfo and both need to be part of you ProductInfo class, you should keep seperate lists:
public class ProductInfo
{
public List<PartInfo> PartInfos { get; set; }
public List<SubProductInfo> SubProductInfos { get; set; }
public string Name { get; set; }
}
public class SubProductInfo : PartInfo
{
public ProductInfo ProductInfo { get; set; }
}
public class PartInfo
{
public string Name { get; set; }
public string Desc { get; set; }
}
Maybe you should avoid inheritence, it helps visualizing your data model.
Edit
The second option won't (de)serialize as SubProductInfo has a circular connection to ProductInfo. You can mark the ProductInfo property as not serializeble and fill it after reading it from json. Or just remove it, since the code that wants to use it should have access to the parent ProductInfo class.

Related

ASMX can't set known type attributes

Im working on ASMX service that allows me to work with databases and their tables. The schema looks like this
[DataContract]
public class DataBase
{
[DataMember]
public string Name { get; set; }
[DataMember]
public List<Table> Tables { get; set; }
...
}
[DataContract]
public class Table
{
[DataMember]
public string Name { get; set; }
[DataMember]
public List<Column> Columns { get; set; }
[DataMember]
public List<List<object>> Data { get; set; }
...
}
[DataContract]
public class Column
{
[DataMember]
public string Name { get; set; }
[ DataMember]
public string Type { get; set; }
...
}
"Data" field is meant to keep a table of all values of different types. The problem is - i have to work with a few of custom types:
public class Email
{
[DataMember]
public string address { get; set; }
...
}
public class Strings : List<string>
{
public Strings(IEnumerable<string> collection) : base(collection) { }
...
}
And the problem is that web service does not create references to these types. I do not use them in methods explicitly, but store in table. Using KnownType and DataContract did not help me, and when i created same classes in a client app, i have exceptions. Please, help?
I fixed it: basically i created dummy methods that returned object of nedded types, deleted the method references from client app and it worked.

How to use automap with object with nested dto?

I am new to Automap, and I am trying to filter out the result. I want to know how to map nested dtos.
Post Entity:
public class Post
{
public Author? Author { get; set; }
[Required] [Key] public int Id { get; set; }
[Required] public string Title { get; set; }
[Required] public string Description { get; set; }
[Required] public string Body { get; set; }
}
PostRead: (dto)
public class PostRead
{
public DateTime Created { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string Description { get; set; }
// Author would work but I want only the AuthorRead data
public AuthorRead Author;
}
Author Entity
public class Author
{
[Key] [Required] public int Id { get; set; }
[Required] public string Name { get; set; }
public IEnumerable<Post> Posts { get; set; }
}
AuthorRead.cs (dto)
public class AuthorRead
{
public int Id { get; set; }
public string Name { get; set; }
}
Technically if I use Author Entity in PostRead, it works but it'll give the list of the posts the Author has, and i want only the information that is in the AuthorRead (so the API response doesn't send the list of posts of the Author itself).
how I can map the object of type Author to the type AuthorRead in the PostRead?
Errors:
AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping.
Mapping types:
Object -> PostRead
System.Object -> OhMyBlogAPI.Models.PostRead
at lambda_method22(Closure , Object , PostRead , ResolutionContext )
at OhMyBlogAPI.Tests.AutomapTests.MockPost_MapsTo_PostRead() in
What I tried , and searching a lot.
CreateMap<Post, PostRead>()
.ForMember(m
=> m.Author, o
=> o.MapFrom<Author, AuthorRead>("Author"));
And profiles (each line represent relevant profiles content):
CreateMap<Post, PostRead>();
CreateMap<Author, AuthorRead>();
My bad, the code works.
I misconfigured something in the Unit testing. I am really sorry.

Passing values from concretized instance of an base class to another base class instance

I am currently working on making viewmodels capable of parsing data extracted from database to the UI and vice versa, and to do so I do a lot of manual mapping between my two viewmodels.
Currently I try to pass some values that determines an attribute, but since each attributetype requires specifying a lot specific parameter, and 90% of the variables will be redundant in all cases since attributes only have one type..
Thus i have create a placeholder base class, which just contains an Id, that each atttribute have,
and each of the specific attribute type parameter will then use this placeholder as base class..
example:
public class BooleanViewSpecification : AttributeTypeSpecification
{
public string TrueOptionText { get; set; }
public string FalseOptionText { get; set; }
}
public class DateTimeTypeViewSpecification : AttributeTypeSpecification
{
public DateTime EarliestDataTime { get; set; }
public DateTime LatestDataTime { get; set; }
}
and my Attribute class is just an
public class AttributeView
{
public DataType Type { get; set; }
public AttributeTypeSpecification AttributeTypeViewSpecification { get; set; }
}
And the same Goes for my DB view model
public class BooleanSpecification : AttributeTypeSpecification
{
public string TrueOptionText { get; set; }
public string FalseOptionText { get; set; }
}
public class DateTimeTypeSpecification : AttributeTypeSpecification
{
public DateTime EarliestDataTime { get; set; }
public DateTime LatestDataTime { get; set; }
}
and my Attribute class is just an
public class Attribute
{
public DataType Type { get; set; }
public AttributeTypeSpecification AttributeTypeSpecification { get; set; }
}
Problem is then mapping from one class to another class
public static IEnumerable<AttributeView> MapToViewModel(this IEnumerable<Attribute> attributes)
{
return attributes.Select(z => new AttributeView()
{
Type = z.Type,
AttributeTypeViewSpecification = z.AttributeTypeSpecification
});
}
Which does not seem to work?
I use entity framework and migrate using Code-First what I receive is the Id of the location, and not the actual values?
I cant seem to understand why I cant be given the values - if it during the mapping does have the value?
So why cant they be mapped over?
I retrieve the value
Context.Include(Attribute).ThenInclude(AttributeTypeSpecification)
The only thing I receive is the actual Id rather than the specified entries?

Creating Objects where multiple objects have the same properties

My program is starting to get pretty big. and i have found that its starting to do the same thing in multiple area's.
Im trying to figure out how i can make it more efficient.
So i have an object that looks like this
public class TreeViewNode
{
public TreeViewNode()
{
Children = new ObservableCollection<TreeViewNode>();
}
public String Name { get; set; }
public string Description { get; set; }
public ObservableCollection<TreeViewNode> Children { get; set; }
}
i also have another object that looks like this;
public class ComputerObject
{
public String Name { get; set; }
public Int32 UUID { get; set; }
public DateTime Created { get; set; }
public ObservableCollection<Object> Children { get; set; }
}
Both these items need to have some of the same properties..
at the moment they both have the Children Property and the Name Property. but they both need to have some other common properties added to them.
so i have tried something like this.
public class BaseObject
{
public String Name { get; set; }
public ObservableCollection<Object> Children { get; set; }
public string Description { get; set; }
public BaseObject()
{
Children = new ObservableCollection<object>();
}
}
public class ComputerObject: BaseObject
{
public Int32 UUID { get; set; }
public DateTime Created { get; set; }
}
public class TreeViewNode: BaseObject
{
public String IconPath { get; set; }
}
Now this is just a cut down version of what i am implementing, i have alot of objects that share the same properties. and some that dont and mix and match. and i cannot figure out the best implimentation for this.
My Objects are becoming very cluttered, and when i rename a property i find that i have to rename it in several area's and this isnt the way its ment to be.
can someone please advise how i would implement multiple objects that share the same property names?
In my opinion you should not let classes inherit from one baseclass when these childclasses are not related to each other (like #Sriram Sakthivel asked Animal < Dog,Cat) just to share the same properties.
You should determine which classes are related (cat, dog are animals; car, motorcycle are vehicles) and then create baseclasses based on these "groupings".
I would look into decorator pattern. In short, you dont share common properties via inheritance. You make classes that contain common properties, and use these classes as properties in your end classes.
EDIT: Example is actually just a standard composition, it should work nevertheless
E.G.
public class Decorator1
{
public String Name { get; set; }
public ObservableCollection<Object> Children { get; set; }
public string Description { get; set; }
}
public class Decorator2
{
public long Id { get; set; }
}
public class ClassA
{
public Decorator1 TreeNodeImpl;
}
public class ClassB
{
public Decorator1 TreeNodeImpl;
public Decorator2 LongIdImpl;
}

C# Table Row to a Dynamic Class

I'm working on application in which the user defines classes using dedicated editor. The result of this step is db table which holds a class name and list of properties attached to it by the user.
The classes can only hold only primitive types, but struct, as parameters.
The next step is to load the table rows as dynamic objects to another application.
Beside using reflection, is there another way to convert table row to POCO?
These are the models:
[Description("represents the base model")]
public class
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Comment { get; set; }
}
public class ParameterModel : BaseModel
{
public string Type { get; set; }
public string DefaultValue { get; set; }
}
[Description("Represents dynamic activity")]
public class ActivityModel : BaseModel
{
public List<ParameterModel> Parameters { get; set; }
}
Thank you very much.

Categories

Resources