【发布时间】:2016-01-06 15:43:20
【问题描述】:
我有一个相当大的对象类,它由一堆原始属性值(int、float、bool、string)定义。我从客户端应用程序获取对象作为 json 字符串,我将其反序列化为 C# .Net 类,以便可以将它们保存到 SQL 数据库。我遇到的问题是序列化程序为浮点参数提供了一个默认值 0,这会破坏我的应用程序,因为未定义的值需要以不同于 0 的方式处理。(注意:如果用户定义了它们,则可以接受 0 值为 0,但我不能假设未定义的值是 0。)
我实际上有数百个这样的原始属性,所以我希望有一种方法可以使这项工作在全局范围内工作,而不必编写自定义属性类型对象。
以下是我将 JSON 字符串反序列化为 C# 对象的方法
using System.Web.Script.Serialization; // Note: used to deserialize JSON objects
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
RootObject obj = JsonConvert.DeserializeObject<RootObject>(JSONObjectFromClient);
这是我的对象类
public class SeatDefinition
{
public string DefinitionID { get; set; }
public string r3_tolType { get; set; }
public float r3_value { get; set; } // Note: this could be 0, but it shouldn't be assumed to be 0 if undefined
public bool r3_verified { get; set; }
public float r4_minus { get; set; } // same here
public float r4_plus { get; set; } // and here
public string r4_tolType { get; set; }
public float r4_value { get; set; } //etc
public bool r4_verified { get; set; }
public float r5_minus { get; set; }
public float r5_plus { get; set; }
public string r5_tolType { get; set; }
public float r5_value { get; set; }
public bool r5_verified { get; set; }
// ... 400 more such attributes
}
谁能帮忙?
编辑 2016-01-05 晚上 11:38 PST 原来我是个白痴。如果您在类定义中声明它们应该是可空的,反序列化器的自动魔法会将值保留为空。为了解决我的问题,我需要做的就是改变
public bool r3_verified { get; set; }
到
public bool? r3_verified { get; set; }
对于那些没有按我需要传入的值,我留下了空值。
感谢@dbc 为我指明了正确的方向。
【问题讨论】:
-
您希望未定义输入的值是多少?
-
如何识别未初始化的值?
-
改为
float?(等等) -
如果未定义比值应该是什么??
标签: c# json serialization json.net