使用像这样的简单类/接口
public interface IThing
{
string Name { get; set; }
}
public class Thing : IThing
{
public int Id { get; set; }
public string Name { get; set; }
}
如何只使用“Name”属性获取JSON字符串(仅限底层接口的属性)?
实际上,当我这样做时:
var serialized = JsonConvert.SerializeObject((IThing)theObjToSerialize, Formatting.Indented);
Console.WriteLine(serialized);
我将完整对象作为JSON(Id + Name);
答案 0 :(得分:23)
我使用的方法,
public class InterfaceContractResolver : DefaultContractResolver
{
private readonly Type _InterfaceType;
public InterfaceContractResolver (Type InterfaceType)
{
_InterfaceType = InterfaceType;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
//IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
IList<JsonProperty> properties = base.CreateProperties(_InterfaceType, memberSerialization);
return properties;
}
}
// To serialize do this:
var settings = new JsonSerializerSettings() {
ContractResolver = new InterfaceContractResolver (typeof(IThing))
});
string json = JsonConvert.SerializeObject(theObjToSerialize, settings);
答案 1 :(得分:16)
受@ user3161686的启发,这是对InterfaceContractResolver
的一个小修改:
public class InterfaceContractResolver<TInterface> : DefaultContractResolver where TInterface : class
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(typeof(TInterface), memberSerialization);
return properties;
}
}
答案 2 :(得分:11)
这里还有另一种变化。代码来自http://www.tomdupont.net/2015/09/how-to-only-serialize-interface.html,其中的其他答案有以下改进
Interface2[]
中有Interface1
,那么它将被序列化。我试图序列化一个WCF代理对象,结果JSON出现为{}
。原来所有属性都设置为Ignore=true
所以我必须添加一个循环来将它们全部设置为不被忽略。
public class InterfaceContractResolver : DefaultContractResolver
{
private readonly Type[] _interfaceTypes;
private readonly ConcurrentDictionary<Type, Type> _typeToSerializeMap;
public InterfaceContractResolver(params Type[] interfaceTypes)
{
_interfaceTypes = interfaceTypes;
_typeToSerializeMap = new ConcurrentDictionary<Type, Type>();
}
protected override IList<JsonProperty> CreateProperties(
Type type,
MemberSerialization memberSerialization)
{
var typeToSerialize = _typeToSerializeMap.GetOrAdd(
type,
t => _interfaceTypes.FirstOrDefault(
it => it.IsAssignableFrom(t)) ?? t);
var props = base.CreateProperties(typeToSerialize, memberSerialization);
// mark all props as not ignored
foreach (var prop in props)
{
prop.Ignored = false;
}
return props;
}
}
答案 3 :(得分:10)
您可以使用条件序列化。看一下这个link。基本上,您需要实现IContractResolver
接口,重载ShouldSerialize
方法并将解析器传递给Json Serializer的构造函数。
答案 4 :(得分:6)
[JsonIgnore]
的替代方法是[DataContract]
和[DataMember]
属性。如果您使用[DataContract]
标记了类,则序列化程序将仅处理使用[DataMember]
属性标记的属性(JsonIgnore
是“选择退出”模型,而DataContract
是“op-在“)。
[DataContract]
public class Thing : IThing
{
[DataMember]
public int Id { get; set; }
public string Name { get; set; }
}
这两种方法的局限性在于它们必须在类中实现,不能将它们添加到接口定义中。
答案 5 :(得分:5)
您可以添加[JsonIgnore]
注释以忽略属性。
答案 6 :(得分:2)
除了@mon给出的答案之外,你可以使用默认的[DataContract]和[DataMember] 看看这个
答案 7 :(得分:2)
我想分享一下我们在面对这项任务时最终会做些什么。考虑到OP的界面和类......
public interface IThing
{
string Name { get; set; }
}
public class Thing : IThing
{
public int Id { get; set; }
public string Name { get; set; }
}
...我们创建了一个直接实现接口的类......
public class DirectThing : IThing
{
public string Name { get; set; }
}
然后简单地序列化我们的Thing
个实例,将其反序列化为DirectThing
,然后将其序列化为DirectThing
:
var thing = new Thing();
JsonConvert.SerializeObject(
JsonConvert.DeserializeObject<DirectThing>(JsonConvert.SerializeObject(thing)));
这种方法可以使用长接口继承链...您只需要在感兴趣的级别进行直接类(在此示例中为DirectThing
)。无需担心反射或属性。
从维护的角度来看,如果将成员添加到DirectThing
,则IThing
类很容易维护,因为如果您还没有将它们放在DirectThing
中,编译器会给出错误。但是,如果您从<{1}} 移除成员X而将其放入IThing
,那么您必须记住将其从Thing
或者X将在最终结果中。
从性能角度来看,这里发生了三次(反)序列化操作而不是一次,因此根据您的情况,您可能希望评估基于反射器/属性的解决方案与此解决方案的性能差异。在我的情况下,我只是在小范围内这样做,所以我不担心一些微/毫秒的潜在损失。
希望能帮助别人!
答案 8 :(得分:1)
最后我知道什么时候不行...... 如果你想在另一个复杂的对象里面,它将无法正确序列化。
所以我制作的版本只会提取存储在特定程序集中的数据以及具有相同基本接口的类型。
所以它是.Net Core JsonContractResolver。
除数据提取外,它还解决了:
a)在向客户发送数据之前进行camelCase转换
b)使用允许范围内的最顶层接口(通过汇编)
c)修复字段顺序:首先列出大多数基类的字段,嵌套对象也符合此规则。
public class OutputJsonResolver : DefaultContractResolver
{
#region Static Members
private static readonly object syncTargets = new object();
private static readonly Dictionary<Type, IList<JsonProperty>> Targets = new Dictionary<Type, IList<JsonProperty>>();
private static readonly Assembly CommonAssembly = typeof(ICommon).Assembly;
#endregion
#region Override Members
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
if (type.Assembly != OutputJsonResolver.CommonAssembly)
return base.CreateProperties(type, memberSerialization);
IList<JsonProperty> properties;
if (OutputJsonResolver.Targets.TryGetValue(type, out properties) == false)
{
lock (OutputJsonResolver.syncTargets)
{
if (OutputJsonResolver.Targets.ContainsKey(type) == false)
{
properties = this.CreateCustomProperties(type, memberSerialization);
OutputJsonResolver.Targets[type] = properties;
}
}
}
return properties;
}
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToCase(Casing.Camel);
}
#endregion
#region Assistants
private IList<JsonProperty> CreateCustomProperties(Type type, MemberSerialization memberSerialization)
{
// Hierarchy
IReadOnlyList<Type> types = this.GetTypes(type);
// Head
Type head = types.OrderByDescending(item => item.GetInterfaces().Length).FirstOrDefault();
// Sources
IList<JsonProperty> sources = base.CreateProperties(head, memberSerialization);
// Targets
IList<JsonProperty> targets = new List<JsonProperty>(sources.Count);
// Repository
IReadOnlyDistribution<Type, JsonProperty> repository = sources.ToDistribution(item => item.DeclaringType);
foreach (Type current in types.Reverse())
{
IReadOnlyPage<JsonProperty> page;
if (repository.TryGetValue(current, out page) == true)
targets.AddRange(page);
}
return targets;
}
private IReadOnlyList<Type> GetTypes(Type type)
{
List<Type> types = new List<Type>();
if (type.IsInterface == true)
types.Add(type);
types.AddRange(type.GetInterfaces());
return types;
}
#endregion
}