android object convert to json,Convert .Net object to JSON object in the view

本文介绍了如何在ASP.NET MVC中替换旧的JavaScriptSerializer为JSON.Net进行对象序列化,以提高性能和避免HTML编码问题。作者提供了一个更新后的HtmlHelper扩展方法,利用Newtonsoft.Json库实现MvcHtmlStringToJson,同时展示了如何在视图中正确使用@Html.Raw()避免HTML编码。建议读者升级到使用JSON.Net的最新版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I use this helper since asp.net mvc 2

public static MvcHtmlString ToJson(this HtmlHelper html, object obj)

{

JavaScriptSerializer serializer = new JavaScriptSerializer();

return MvcHtmlString.Create(serializer.Serialize(obj));

}

public static MvcHtmlString ToJson(this HtmlHelper html, object obj, int recursionDepth)

{

JavaScriptSerializer serializer = new JavaScriptSerializer();

serializer.RecursionLimit = recursionDepth;

return MvcHtmlString.Create(serializer.Serialize(obj));

}

And in the view:

var s = @(Html.ToJson(Model.Content));

I should replace serializer with the JSON.Encode(..) now, like mentionned in the refer by Hemant. (It use itself JavaScriptSerializer).

The source of your problem is the "@" which HTML encode the JSON. You can use @Html.Raw(..) to avoid this behavior.

+: take a look for Json.Net http://json.codeplex.com/

JSON.Net update

I've updated the helper a while ago with JSON.net (much better).

It seems some users continue to read, upvote and use the old code. I'd like they use a better way, with the new version below, or by using NGon like Matthew Nichols has noticed it in a comment.

Here's the code:

using System;

using Newtonsoft.Json;

namespace System.Web.Mvc

{

public static class HtmlHelperExtensions

{

private static readonly JsonSerializerSettings settings;

static HtmlHelperExtensions()

{

settings = new JsonSerializerSettings();

// CamelCase: "MyProperty" will become "myProperty"

settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

}

public static MvcHtmlString ToJson(this HtmlHelper html, object value)

{

return MvcHtmlString.Create(JsonConvert.SerializeObject(value, Formatting.None, settings));

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值