我想知道使用c#序列化数据属性(例如array(1) { [0]=> array(5) { ["user"]=> NULL ["ratingSpeed"]=> string(6) "0.0000" ["ratingQuality"]=> string(6) "0.0000" ["ratingResponsibility"]=> string(6) "0.0000" ["ratingTotal"]=> string(10) "0.00000000" } }
)中对象的最可靠方式是什么。我想使用 $ .data()获取此数据,如果数据没有以良好的方式写入(例如空格),则jquery无法获取正确的对象并返回字符串。
我可以完全访问JSON.Net库。
答案 0 :(得分:2)
使用它。例如,在Razor语法中:
<div class="my-component" data-options="@JsonConvert.SerializeObject(new
{
active = true,
name = "Foo",
// ...
})">
</div>
消费:
jQuery(function($) {
$('.my-component').each(function() {
var component = $(this);
var options = component.data('options');
component.somePlugin(options);
});
})
JsonConvert.SerializeObject()
将确保对象呈现为有效的JSON,无论是否存在任何奇怪的字符(如反斜杠)。 Razor的@
语法将确保为HTML上下文正确编码生成的JSON,因此<
之类的符号也不会导致问题。