Json.net 序列化特定的私有字段 [英] Json.net serialize specific private field

查看:57
本文介绍了Json.net 序列化特定的私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class TriGrid
{
    private List<HexTile> _hexes;
    //other private fields...
    //other public proprerties
}

我的目标是仅序列化 _hexes 字段,因此我创建了以下 ContractResolver:

My goal is to serialize only the _hexes field, so I created the following ContractResolver:

internal class TriGridContractResolver : DefaultContractResolver
{
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        return new List<MemberInfo> { objectType.GetMember("_hexes", BindingFlags.NonPublic | BindingFlags.Instance)[0] };
    }
}

当我想序列化 TriGrid 的一个实例时,我会这样做:

and when I want to serialize an instance of TriGrid I do:

var settings = new JsonSerializerSettings()
{
    ContractResolver = new TriGridContractResolver()
};
var json = JsonConvert.SerializeObject(someTriGrid, settings);
string strintJson = json.ToString();

但是当我检查 strintJson 的值时总是 "{}"._hexes 有元素,不为空.如果我序列化一个特定的 HexTile,它会按预期工作.我在这里做错了什么?

but when I check the value of strintJson is always "{}". The _hexes has elements, it is not empty. If I serialize one particular HexTile it works as expected. What I am doing wrong here?

推荐答案

无需实现自定义DefaultContractResolver.解决方案是将 [JsonProperty] 放在 _hexes 上,将 [JsonIgnore] 放在所有其他属性和字段上.

There is no need to implement a custom DefaultContractResolver. The solution is to put [JsonProperty] on _hexes and [JsonIgnore] on all the other properties and fields.

这篇关于Json.net 序列化特定的私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆