Ser*_*rge 11 c# serialization json asp.net-mvc-5
namespace Booking.Areas.Golfy.Models
{
public class Time
{
public string time { get; set; }
public int holes { get; set; }
public int slots_available { get; set; }
public decimal? price { get; set; }
public int? Nextcourseid { get; set; }
public bool ShouldSerializeNextcourseid
{
get
{
return this.Nextcourseid != null;
}
}
public bool? allow_extra { get; set; }
public bool ShouldSerializeallow_extra
{
get
{
return this.allow_extra != null;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
namespace Booking.Areas.Golfy.Controllers
{
public class TeetimesController : Controller
{
//
// GET: /Golfy/Teetimes/
public ActionResult Index(
string date,
int? courseid = null,
int? clubid = null,
int? holes = null,
int? available = null,
int? prices = null
)
{
var DateFrom = DateTime.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Teetimes r = BookingManager.GetBookings(new Code.Classes.Params.ParamGetBooking()
{
ClubID = clubid
, DateFrom = DateFrom
, DateTo = DateFrom.AddDays(1)
, GroundID = courseid
});
return Json(r, JsonRequestBehavior.AllowGet);
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的webservice返回一个json字符串,其中包含几个Time of Time.
我希望属性Nextcourseid和allow_extra在它们的值为null时被排除在输出之外.
我试过ShouldSerializeXxx,但它似乎不起作用.
仅供参考:我也试过[ScriptIgnore]哪个有效,但不是有条件的.
Dav*_*trg 12
您不能使用默认值Json ActionResult
删除null属性.
您可以查看JSON.NET,它有一个属性,您可以设置该属性,如果它为null,则删除该属性
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
Run Code Online (Sandbox Code Playgroud)
或者如果您不想使用其他库,您可以创建自己的json自定义ActionResult并为默认注册一个新的转换器JavaScriptSerializer
,如下所示:
public class JsonWithoutNullPropertiesResult : ActionResult
{
private object Data { get; set; }
public JsonWithoutNullPropertiesResult(object data)
{
Data = data;
}
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/x-javascript";
response.ContentEncoding = Encoding.UTF8;
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new NullPropertiesConverter() });
string ser = serializer.Serialize(Data);
response.Write(ser);
}
}
}
public class NullPropertiesConverter : JavaScriptConverter
{
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var toSerialize = new Dictionary<string, object>();
foreach (var prop in obj.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Select(p => new
{
Name = p.Name,
Value = p.GetValue(obj)
})
.Where(p => p.Value != null))
{
toSerialize.Add(prop.Name, prop.Value);
}
return toSerialize;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return GetType().Assembly.GetTypes(); }
}
}
Run Code Online (Sandbox Code Playgroud)
现在在你看来:
public ActionResult Index()
{
Teetimes r = BookingManager.GetBookings();
return new JsonWithoutNullPropertiesResult(t);
}
Run Code Online (Sandbox Code Playgroud)
我总是遇到框架嵌入的 json 序列化器的问题,因此我使用Json.NET。这是测试这两个序列化器的小示例:
public class Model {
public int Id { get; set; }
public string Name { get; set; }
public bool ShouldSerializeName() {
return Name != null;
}
}
class Program {
static void Main(string[] args) {
var t1 = new Model {
Name = "apw8u3rdmapw3urdm",
Id = 298384
};
var t2 = new Model {
Id = 234235
};
Test(t1);
Test(t2);
}
static void Test(Model model) {
Console.WriteLine("JSon from .Net: {0}", ToJson(model));
Console.WriteLine("JSon from JSon.Net: {0}", ToDotNetJson(model));
}
static string ToJson(Model model) {
var s = new JavaScriptSerializer();
return s.Serialize(model);
}
static string ToDotNetJson(Model model) {
return JsonConvert.SerializeObject(model);
}
}
Run Code Online (Sandbox Code Playgroud)
您必须System.Web.Extensions
作为依赖项包含并Json.Net
使用 nuget 安装才能使示例正常工作。
以下是Json.NET和框架嵌入式序列化程序的一些文档
归档时间: |
|
查看次数: |
11053 次 |
最近记录: |