我有一种情况,我从网络服务获得一个对象,比如说
MyObject{
public bool MyProp
}
我无法修改该对象, 但我需要将MyObject序列化为json字符串,但MyProp必须转换为1或0而不是true / false。
我正在使用JavaScriptSerializer序列化为Json
有什么想法吗?
TKS
答案 0 :(得分:2)
如果您愿意切换到json.net,可以使用Convert an int to bool with Json.Net中的解决方案。
如果您希望继续使用JavaScriptSerializer
,则需要为MyObject
类型创建JavaScriptConverter
,如下所示:
class MyObjectConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new[] { typeof(MyObject) }; }
}
// Custom conversion code below
const string myPropName = "MyProp";
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
object value;
if (dictionary.TryGetValue(myPropName, out value))
{
dictionary[myPropName] = !value.IsNullOrDefault();
}
var myObj = new JavaScriptSerializer().ConvertToType<MyObject>(dictionary);
return myObj;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var myObj = (MyObject)obj;
// Generate a default serialization. Is there an easier way to do this?
var defaultSerializer = new JavaScriptSerializer();
var dict = defaultSerializer.Deserialize<Dictionary<string, object>>(defaultSerializer.Serialize(obj));
dict[myPropName] = myObj.MyProp ? 1 : 0;
return dict;
}
}
public static class ObjectExtensions
{
public static bool IsNullOrDefault(this object value)
{
// Adapted from https://stackoverflow.com/questions/6553183/check-to-see-if-a-given-object-reference-or-value-type-is-equal-to-its-default
if (value == null)
return true;
Type type = value.GetType();
if (!type.IsValueType)
return false; // can't be, as would be null
if (Nullable.GetUnderlyingType(type) != null)
return false; // ditto, Nullable<T>
object defaultValue = Activator.CreateInstance(type); // must exist for structs
return value.Equals(defaultValue);
}
}
然后使用它:
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new MyObjectConverter() } );
var json = serializer.Serialize(myObject);
注意 - 即使你的MyObject
类只有一个属性,我也会假设在现实生活中它可以有其他属性应该自动序列化和反序列化,例如:
public class MyObject
{
public bool MyProp { get; set; }
public string SomeOtherProperty { get; set; }
}