[英]C# Newtonsoft - Deserialize JSON into concrete based on property name
[英]C# Using Newtonsoft Json to change Property Name of Item in List based upon an Attribute
我試圖通過引用列表上的屬性來更改列表內屬性的名稱。
下面是一個外部類 A 的代碼,其中包含一個 B 的列表。如果您注意到,在“A”上有 [DataMember, ItemName("C")]。 簡而言之,我想使用這個“ItemName”屬性將 B 中的“Data”屬性重命名為“C”
代碼:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace ConsoleApp1
{
public class B
{
[DataMember]
public int Data { get; set; }
}
public class A
{
[DataMember, ItemName("C")]
public List<B> List { get; set; }
}
public class ItemNameAttribute : Attribute
{
public string Name { get; }
public ItemNameAttribute(string name)
{
Name = name;
}
}
class Program
{
static void Main(string[] args)
{
var a = new A();
a.List = new List<B>()
{
new B() { Data = 1 }, new B() { Data = 2 }
};
var json = JsonConvert.SerializeObject(a);
}
}
}
我想要的預期 Json 輸出是
{
"List": [
{
"C": 1
},
{
"C": 2
}
]
}
我的當前輸出是:
{
"List": [
{
"Data": 1
},
{
"Data": 2
}
]
}
您可以使用 JsonPropertyAttribute 來更改屬性的名稱。
這是源代碼。
public class B
{
[JsonProperty("C")]
public int Data { get; set; }
}
public class A
{
[JsonProperty("List")]
public List<B> List { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.