使用不同的字段名称将{JSON有效负载映射到DTO

时间:2017-08-30 09:55:30

标签: c# asp.net-core-mvc .net-core

我有一个简单的GitHub有效负载传入我的ASP.NET核心应用程序,我想知道如何将我收到的有效负载映射到我的DTO。

示例DTO

public class GithubPayload
{
    public string Action { get; set; }  // action
    public string Name { get; set; }    // pull_request.title
}

示例有效负载

{
  "action": "deleted",
  "pull_request": {
    "title": "Fix button"
  }
}

2 个答案:

答案 0 :(得分:3)

您可以在JsonProperty上使用Action属性,并在名称上使用可以解释嵌套属性的自定义转换器。检查Json.Net的JsonConverter

public class GithubPayload {
    [JsonProperty("action")]
    public string Action { get; set; }
    [JsonConverter(typeof(NestedConverter), "pull_request.title")]
    public string Name { get; set; }
}

NestedConverter是一个自定义JsonConverter,它将读取嵌套属性

public class NestedConverter : JsonConverter {
    private readonly string path;

    public NestedConverter (string path) {
        this.path = path; 
    }

    //...to do
}

更新

使用JsonConverter转换有效负载本身也可以正常工作

public class GithubPayloadConverter : JsonConverter {

    public override bool CanConvert(Type objectType) {
        return objectType == typeof(GithubPayload);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        dynamic data = JObject.Load(reader);
        var model = new GithubPayload {
            Action = data.action,
            Name = data.pull_request.title
        };
        return model;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        throw new NotImplementedException();
    }
}

并装饰课程本身

[JsonConverter(typeof(GithubPayloadConverter))]
public class GithubPayload {
    public string Action { get; set; }
    public string Name { get; set; }
}

反序列化就是

string json = @"{ 'action': 'deleted', 'pull_request': { 'title': 'Fix button' } }";

var payload = JsonConvert.DeserializeObject<GithubPayload>(json);

答案 1 :(得分:2)

只是一个想法:

using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using System.IO;

namespace WebApplication1
{
    public class Program
    {
        public class GithubPayload
        {
            public string Action { get; set; }  // action
            public string Name { get; set; }    // pull_request.title
        }

        public static void Main(string[] args)
        {
            string json = @"{
  ""action"": ""deleted"",
  ""pull_request"": {
                ""title"": ""Fix button""
  }
        }";

            dynamic obj = JsonConvert.DeserializeObject(json);

            GithubPayload entity = new GithubPayload();
            entity.Action = obj.action;
            entity.Name = obj.pull_request.title;

            ..................
        }
    }
}

测试了这个解决方案,它可以工作。