将JSON对象映射到POCO

时间:2017-07-31 10:42:43

标签: c# json.net automapper

我想知道是否可以从json对象映射到poco对象。

我正在尝试反序列化和映射的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": ""
            }]
        }
    ]
}

我想要映射的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; }       
}

和我正在使用的映射

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;
    }
}

我正在尝试执行的代码

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

当我执行上面的行时,CustomersDTO.Customers属性具有来自json数组的正确数量的客户对象,但嵌套的CustomerDTO.Customer和CustomerDTO.Subscriptions属性为null。

我不确定我是否正确地执行此操作我需要使用json对象中的正确值填充这些属性。

2 个答案:

答案 0 :(得分:2)

这是从您的JSON创建的C#类。使用它,尝试映射 - (您可以使用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; }
}

答案 1 :(得分:0)

很晚,但今天我在POC中使用了

Data.json

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

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

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

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);
    }
}