简体   繁体   English

将JSON对象映射到POCO

[英]Map JSON object to POCO

I would like to know if it is possible to map from a json object to a poco object. 我想知道是否可以从json对象映射到poco对象。

The json object I am trying to deserialize and map: 我试图反序列化和映射的json对象:

    {
    "customers": [{
            "customerid": "",
            "firstname": "",
            "lastname": "",
            "companyname": "",
            "email": "",
            "language": "",
            "culture": "",
            "addressline1": "",
            "addressline2": "",
            "city": "",
            "country": "",
            "phonenumber": "",
            "postalcode": "",
            "region": "",
            "state": "",
            "domain": "",
            "partnerid": "",
            "subscriptions": [{
                "id": "",
                "offerid": "",
                "offername": "",
                "friendlyname": "",
                "quantity": "",
                "parentsubscriptionid": "",
                "creationdate": "",
                "effectivestartdate": "",
                "commitmentenddate": "",
                "status": "",
                "autorenewenabled": "",
                "billingtype": "",
                "partnerbillingcycle": "",
                "partnerid": "",
                "orderid": "",
                "offerlink": "",
                "parentsubscriptionlink": ""
            }]
        },
        {
            "customerid": "",
            "firstname": "",
            "lastname": "",
            "companyname": "",
            "email": "",
            "language": "",
            "culture": "",
            "addressline1": "",
            "addressline2": "",
            "city": "",
            "country": "",
            "phonenumber": "",
            "postalcode": "",
            "region": "",
            "state": "",
            "domain": "",
            "partnerid": "",
            "subscriptions": [{
                "id": "",
                "offerid": "",
                "offername": "",
                "friendlyname": "",
                "quantity": "",
                "parentsubscriptionid": "",
                "creationdate": "",
                "effectivestartdate": "",
                "commitmentenddate": "",
                "status": "",
                "autorenewenabled": "",
                "billingtype": "",
                "partnerbillingcycle": "",
                "partnerid": "",
                "orderid": "",
                "offerlink": "",
                "parentsubscriptionlink": ""
            }]
        },
        {
            "customerid": "",
            "firstname": "",
            "lastname": "",
            "companyname": "",
            "email": "",
            "language": "",
            "culture": "",
            "addressline1": "",
            "addressline2": "",
            "city": "",
            "country": "",
            "phonenumber": "",
            "postalcode": "",
            "region": "",
            "state": "",
            "domain": "",
            "partnerid": "",
            "subscriptions": [{
                "id": "",
                "offerid": "",
                "offername": "",
                "friendlyname": "",
                "quantity": "",
                "parentsubscriptionid": "",
                "creationdate": "",
                "effectivestartdate": "",
                "commitmentenddate": "",
                "status": "",
                "autorenewenabled": "",
                "billingtype": "",
                "partnerbillingcycle": "",
                "partnerid": "",
                "orderid": "",
                "offerlink": "",
                "parentsubscriptionlink": ""
            }]
        }
    ]
}

the DTO that I am trying to map to 我想要映射到的DTO

public class CustomersDTO
{
    public List<CustomerDTO> Customers { get; set; }
}

public class CustomerDTO
{
    public BE.Customer Customer { get; set; }

    public List<BE.Subscription> Subscriptions { get; set; }       
}

and the mapping I am using 和我正在使用的映射

CreateMap<JObject, CustomersDTO>()
       .ForMember("Customers", cfg => { cfg.MapFrom(jo => jo["customers"]); })                                    
        ;

CreateMap<JObject, BE.Customer>()
   .ForMember("CustomerGUID", cfg => { cfg.MapFrom(jo => jo["customerid"]); })
   .ForMember("FirstName", cfg => { cfg.MapFrom(jo => jo["firstname"]); })
   .ForMember("Surname", cfg => { cfg.MapFrom(jo => jo["lastname"]); })
   .ForMember("CompanyName", cfg => { cfg.MapFrom(jo => jo["companyname"]); })
   .ForMember("Email", cfg => { cfg.MapFrom(jo => jo["email"]); })
   .ForMember("PreferredLanguage", cfg => { cfg.MapFrom(jo => jo["language"]); })
   .ForMember("PreferredCurrency", cfg => { cfg.MapFrom(jo => jo["culture"]); })
   .ForMember("Address1", cfg => { cfg.MapFrom(jo => jo["addressline1"]); })
   .ForMember("Address2", cfg => { cfg.MapFrom(jo => jo["addressline2"]); })
   .ForMember("Address3", cfg => { cfg.MapFrom(jo => jo["city"]); })
   .ForMember("Address4", cfg => { cfg.MapFrom(jo => jo["state"]); })
   .ForMember("MobileNumber", cfg => { cfg.MapFrom(jo => jo["phonenumber"]); })
   .ForMember("PostalCode", cfg => { cfg.MapFrom(jo => jo["postalcode"]); })
   .ForMember("Region", cfg => { cfg.MapFrom(jo => jo["region"]); })
   .ForMember("CSPDomain", cfg => { cfg.MapFrom(jo => jo["domain"]); })             
   ;

CreateMap<JObject, BE.Subscription>()
   .ForMember("OfferId", cfg => { cfg.MapFrom(jo => jo["offerid"]); })
   .ForMember("OfferId", cfg => { cfg.MapFrom(jo => jo["offerid"]); })
   .ForMember("Quantity", cfg => { cfg.MapFrom(jo => jo["quantity"]); })
   .ForMember("FriendlyName", cfg => { cfg.MapFrom(jo => jo["friendlyname"]); })
   .ForMember("AssignedDate", cfg => { cfg.MapFrom(jo => jo["creationdate"]); })
   .ForMember("Status", cfg => { cfg.MapFrom(jo => jo["status"]); })
   .ForMember("OfferURI", cfg => { cfg.MapFrom(jo => jo["offerlink"]); })
   ;

public class AutoMapperConfiguration
{
    public MapperConfiguration Configure()
    {
        var config = new MapperConfiguration(cfg =>
        {                
            cfg.AddProfile<CustomerProfile>();
        });

        return config;
    }
}

the code I am trying to execute 我试图执行的代码

var customersJsonObj = JObject.Parse(jsonText);
var customers = Mapper.Map<CustomersDTO>(customersJsonObj);

When I execute the line above the CustomersDTO.Customers property has the correct number of customer objects from the json array but the nested CustomerDTO.Customer and CustomerDTO.Subscriptions properties are null. 当我执行上面的行时,CustomersDTO.Customers属性具有来自json数组的正确数量的客户对象,但嵌套的CustomerDTO.Customer和CustomerDTO.Subscriptions属性为null。

I am not sure if I am doing this correctly I need these properties populated with the correct values from the json object. 我不确定我是否正确地执行此操作我需要使用json对象中的正确值填充这些属性。

Here is the C# class, created from your JSON. 这是从您的JSON创建的C#类。 Using this, try mapping - (you can use http://json2csharp.com to Convert your JSON into c# code) 使用这个,尝试映射 - (您可以使用http://json2csharp.com将您的JSON转换为c#代码)

public class Subscription
{
    public string id { get; set; }
    public string offerid { get; set; }
    public string offername { get; set; }
    public string friendlyname { get; set; }
    public string quantity { get; set; }
    public string parentsubscriptionid { get; set; }
    public string creationdate { get; set; }
    public string effectivestartdate { get; set; }
    public string commitmentenddate { get; set; }
    public string status { get; set; }
    public string autorenewenabled { get; set; }
    public string billingtype { get; set; }
    public string partnerbillingcycle { get; set; }
    public string partnerid { get; set; }
    public string orderid { get; set; }
    public string offerlink { get; set; }
    public string parentsubscriptionlink { get; set; }
}

public class Customer
{
    public string customerid { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string companyname { get; set; }
    public string email { get; set; }
    public string language { get; set; }
    public string culture { get; set; }
    public string addressline1 { get; set; }
    public string addressline2 { get; set; }
    public string city { get; set; }
    public string country { get; set; }
    public string phonenumber { get; set; }
    public string postalcode { get; set; }
    public string region { get; set; }
    public string state { get; set; }
    public string domain { get; set; }
    public string partnerid { get; set; }
    public List<Subscription> subscriptions { get; set; }
}

public class RootObject
{
    public List<Customer> customers { get; set; }
}

Very late but today I used in my POC 很晚但今天我用在我的POC中

Data.json Data.json

{
"Id": 1,
"FirstName": "Pankaj",
"LastName": "Rawat",
"Address": {
"Street": "Old Post Office",
"City": "Lansdowne",
"State": "Uttrakhand"
}
}

EmployeeProfile.cs EmployeeProfile.cs

public class EmployeeProfile : Profile
{
    public EmployeeProfile()
    {
        CreateMap<JObject, EmployeeDTO>()
            .ForMember(dest => dest.Id, o => o.MapFrom(j => j["Id"]))
            .ForMember(dest => dest.FirstName, o => o.MapFrom(j => j["FirstName"]))
            .ForMember(dest => dest.LastName, o => o.MapFrom(j => j["LastName"]))
            .ForMember(dest => dest.Address, o => o.MapFrom(j => string.Concat(j["Address"]["Street"].ToString(), " ", j["Address"]["City"].ToString(), " ", j["Address"]["State"].ToString())));
    }
}

AutoMapperConfiguration.cs AutoMapperConfiguration.cs

internal class AutoMapperConfiguration
{
    public static void Configure()
    {
        AutoMapper.Mapper.Initialize(x => x.AddProfile<EmployeeProfile>());
    }
}

Program.cs Program.cs中

internal class Program
{
    private static void Main(string[] args)
    {
        var json = File.ReadAllText("data.json");
        JObject jObject = JObject.Parse(json);
        AutoMapperConfiguration.Configure();
        var result = AutoMapper.Mapper.Map<EmployeeDTO>(jObject);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM