简体   繁体   中英

Mapping object with properties names and values

I have class

public class Foo 
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }    
}

I want to convert the object to a generic object

{
    "properties": {
        "id" : "1234",
        "name": "John Doe",
        "email" : "john.doe@mail.com"
    }
}

I want to convert the class instance to the structure where the properties would be dynamic depending on the class. Is this possible with Automapper?

Seems you want to serialize/deserialize to/from JSON. In this case you can reference to Newtonsoft.Json and use the JsonConvert.SerializeObject / JsonConvert.DeserializeObject generic method which does not depend on any specific class:

Deserializing (From String to Class Instance):

var foo = JsonConvert.DeserializeObject<Foo>(jsonString);

Serializing (From Class Instance to String):

var stringValue = JsonConvert.SerializeObject(foo)

One More Point (Mapping)

Also you may want to decorate your class with some attributes to specify the mapping:

[DataContract]
public class Foo 
{
    [DataMember(Name = "id")]
    public string Id {get;set;}

    [DataMember(Name = "name")]
    public string Name {get;set;}

    [DataMember(Name = "email")]
    public string Email {get;set;}    
}

Partially AutoMapper cannot map to dictionary or ExpandoObject, so no.

The following solution was posted before I was aware that by mapping to an ExpandoObject Automapper will simply leave you with an empty object.

The simplest solution would be this I think (assuming you want an ExpandoObject as a result):

public ExpandoObject Map<TInput>(TInput inputObject)
{
  dynamic result = new ExpandoObject();
  result.properties = Mapper.DynamicMap<TInput, ExpandoObject>(inputObject);
  return (ExpandoObject)result;
}

As far as I know you can't delegate all members as child properties to another field using automapper, but it's simple to do this yourself. AutoMapper is completely useless here.

edit: seems that automapper struggles with ExpandoObject... Actually it seems like AutoMapper cannot do this at all, so you're left with reflection.

You would then write a reflection object that can create or populate a dictionary with the objects properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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