c# - 如何 JSON 序列化实体类?
问题描述
我正在尝试将一个复杂对象添加到 Redis 中,但是在从 Redis 检索值时,我将某些值设为空。下面是我正在尝试的粗略示例。我有一个复杂对象,我使用 JsonConvert 序列化该复杂对象并将其添加到 Redis 中。属性 CollectionID 有两个具有各自值的计数,但在从 Redis 获取它并反序列化后,该值将变为 null。
问题是“客户”类是一个实体对象,而 json 序列化无法序列化该特定对象c#。这种情况有什么可能的解决方案吗?
class Program
{
private static IDatabase _cache;
private static ConnectionMultiplexer _connection;
static void Main(string[] args)
{
_connection = ConnectionMultiplexer.Connect("localhost");
_cache = _connection.GetDatabase();
List<Id> id = new List<Id>() { new Id() { ID = 10 }, new Id() { ID = 20 } };
Collection<Customers> collection = new Collection<Customers>() { new Customers(id) };
Product product = new Product(new Guid(), collection, 1);
_cache.StringSet("Redis_Key", GetSerializedString(product));
var value = JsonConvert.DeserializeObject<Product>(_cache.StringGet("Redis_Key"));
}
private static String GetSerializedString<Test1>(Test1 value)
{
return JsonConvert.SerializeObject(
value,
Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.All
});
}
}
public class Product
{
public Product(
Guid parentGuid,
Collection<Customers> collection,
int number)
{
_parentGuid = parentGuid;
_collection = collection;
_number = number;
}
private Guid _parentGuid;
public Guid ParentGuid
{
get { return _parentGuid; }
}
private Collection<Customers> _collection;
public Collection<Customers> Collection
{
get { return _collection; }
}
private int _number;
public int number
{
get { return _number; }
}
}
public class Customers : Entity
{
.
.
.
public Customers(IEnumerable<Id> id)
{
_id = id;
}
private IEnumerable<Id> _id;
public IEnumerable<Id> CollectionID
{
get { return _id; }
}
.
.
.
}
public class Id
{
public int ID { get; set; }
}
解决方案
我认为问题在于您的公共属性没有仅设置器的获取器。
请尝试添加设置器并再次检查。
我希望这会有所帮助:)
推荐阅读
- python - 如何防止打印值时出现空格
- sql-server - 使用pyodbc库在sql连接字符串中混合字符串和输入变量 - Python
- python - 当c没有继承时,每个对象如何与pyObject相关
- vba - 如何在页眉的 Word 文档的每一页上插入特定图像(来自 URL)
- java - 用允许的不出现替换字符串中的所有连续重复项
- eclipse - 无法使用团队资源管理器克隆 TFS Git 存储库
- java - 无法在 web.xml 中加载用户定义的过滤器:com.xxx.CORSFilter
- ansible - Ansible 似乎没有从清单文件中加载 ansible_python_interpreter=/usr/bin/python3 变量
- jinja2 - 使用 jinja 表达式比较 state.sls 中的两个粒度值
- xslt - 如何用xslt中不同标签中的值替换花括号内的变量