使用Json.NET将嵌套的JSON反序列化为平面类 [英] Deserialize nested JSON to a flat class using Json.NET
问题描述
给出以下嵌套的JSON字符串:
Given the following nested JSON string:
string s = @"
{
""id"": 10,
""fields"":{
""issuetype"": {
""name"": ""Name of the jira item""
}
}
}";
如何使用JsonPropertyAttribute
将其反序列化为以下"flattened"类:
How can I deserialize it to the following "flattened" class, using the JsonPropertyAttribute
:
public class JiraIssue
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("fields/issuetype/name")]
public string Type { get; set; }
}
我正在尝试基于/
指定一个导航"规则作为JSON属性名称中的分隔符.
I'm trying to specify a "navigation" rule based on /
as a separator in the name of the JSON property.
基本上,我想指定JsonProperty("fields/issuetype/name")
用作嵌套属性fields.issuetype.name
的导航规则,该属性显然不起作用:
Basically, I want to specify that JsonProperty("fields/issuetype/name")
should be used as a navigation rule to the nested property fields.issuetype.name
, which obviously does not work:
var d = Newtonsoft.Json.JsonConvert.DeserializeObject<JiraIssue>(s);
Console.WriteLine("Id:" + d.Id);
Console.WriteLine("Type" + d.Type);
以上内容仅识别ID:
Id: 10
Type:
要告诉Json.NET使用"/"作为所需嵌套属性的导航路径,我必须实现什么?
What do I have to implement to tell Json.NET to use the "/" as a navigation path to the desired nested property?
推荐答案
这是一种可能的方法-
internal class ConventionBasedConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(JiraIssue).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var daat = JObject.Load(reader);
var ret = new JiraIssue();
foreach (var prop in ret.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance))
{
var attr = prop.GetCustomAttributes(false).FirstOrDefault();
if (attr != null)
{
var propName = ((JsonPropertyAttribute)attr).PropertyName;
if (!string.IsNullOrWhiteSpace(propName))
{
var conventions = propName.Split('/');
if (conventions.Length == 3)
{
ret.Type = (string)((JValue)daat[conventions[0]][conventions[1]][conventions[2]]).Value;
}
ret.Id = Convert.ToInt32(((JValue)daat[propName]).Value);
}
}
}
return ret;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
}
var settings = new JsonSerializerSettings();
settings.Converters.Add(new ConventionBasedConverter());
var o = JsonConvert.DeserializeObject<JiraIssue>(s, settings);
这篇关于使用Json.NET将嵌套的JSON反序列化为平面类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!