Pro-n-apps
Pro-n-apps

Reputation: 55

Convert One Object Model one to another Object Model

I have 2 Models

Model1= OrderItemAll

 public partial class OrderItemAll
{
    public string ProductCode { get; set; }
    public int po_order_no { get; set; }
    public string po_backorder_flag { get; set; }
    public string EAGTIN { get; set; }
    public string INGTIN { get; set; }
    public string OUGTIN { get; set; }
}

Model 2

 public class Consolidate
    {
        public string ProductCode { get; set; }
        public int po_order_no { get; set; }
        public string po_backorder_flag { get; set; }
    }

In JSON I am getting data in OrderItemAll (Model1) format I want to convert it to Consolidate (Model2). I Had look around I got some Mapper or AutoMapper classes But I do not want to use it. Can anyone give me any other option? Thank You

Upvotes: 1

Views: 214

Answers (3)

Maxim Zabolotskikh
Maxim Zabolotskikh

Reputation: 3367

I'd go with an external package like AutoMapper. Than it's just

Mapper.Initialize(c =>
{
    c.CreateMap<OrderItemAll, Consolidate>();
});

And when you want to use it it's

Mapper.Map<Consolidate>(myOrderItemAll);

If your fields are not named the same, you still can add some custom logic in a central place, where you specify, how the fields should be mapped.

Upvotes: 0

lazydeveloper
lazydeveloper

Reputation: 961

I suggest you should use something like AutoMapper.Alternatively you can de-serialize model data(json format) using below function

        /// <summary>
        /// Deserialise json to Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonData"></param>
        /// <returns></returns>


 public T ParseJSONtoObject<T>(string jsonData)
        {           
                        T obj =  JsonConvert.DeserializeObject<T>(jsonData);
              return obj;

        }

calling above method to deserialize json to model

 var model=  ParseJSONtoObject<Consolidate>(jsonData);   

Upvotes: 0

Rahul
Rahul

Reputation: 77876

Given that your class member names are same in both types as in below

 public class Consolidate
    {
        public string ProductCode { get; set; }
        public int po_order_no { get; set; }
        public string po_backorder_flag { get; set; }
    }

You can deserialize it to Consolidate type directly like below, other memebrs will get lost in the process of deserialization.

JSonConvert.DeserializeObject<Consolidate>(jsonsdrializedData);

Upvotes: 1

Related Questions