2

Say I have this C# dictionary:

Dictionary<string, object> Parameters { get; set; }

then I put some values inside

Parameters["param1"] = "val1";
Parameters["param2"] = "val2";

and finally I serialize it with

var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
var writer = new JsonTextWriter(stringWriter);
writer.QuoteName = false;
writer.QuoteChar = '\'';
serializer.Serialize(writer, Parameters);

(I know there are quicker ways, but I need the quoting char to be a single quote and unquoted names).

The result is as expected:

{ 
   param1: 'val1', 
   param2: 'val2' 
}

But what if I want to include a property with an unquoted value, which may represent a function or an object name? For example, how do I get this result:

{ 
   param1: 'val1', 
   param2: 'val2',
   funcReference: someFunctionName,
   objName: valueWithoutQuotes
}

EDIT:

Due to some responses about my JSON syntax saying it's not valid, let me clarify why I need stuff to be unquoted:

I'm using Knockoutjs for Javascript & HTML data-binding. Therefore I need to write something like this - <div data-bind="something: 'value', event: funcName">...</div>

I need single quotes so that it won't mess my HTML and I don't quote the properties names because of my personal style which is very common and is perfectly fine in Javascript (I'm not using it for data exchange).

I need some values to be unquoted so that Knockout will know it's a reference to a function, otherwise it'll treat it as a string. And the names of the functions I'm generating on server, along with other properties and values.

I can of course always build and concat the JSON manually, but I'm looking for some automatic way.

Thanks!

4

2 回答 2

2

(我知道有更快的方法,但我需要引用字符是单引号和不带引号的名称

抱歉,这不是有效的 JSON。在 JSON 中,所有成员都应该用双引号引起来(数字类型除外),并且您不能拥有函数。.NET 中没有会生成无效 JSON 的 JSON 序列化程序。如果您需要生成无效的 JSON,则必须使用字符串连接手动完成,甚至不要尝试使用序列化程序。

这是有效 JSON 编码对象的语法。你必须坚持下去。不要只将术语JSON用于任何 javascript 语法,因为 JSON 具有需要遵守的非常具体的规则。

于 2012-09-24T07:33:53.990 回答
0

添加到我上面的评论中,理想情况下应该是

{  
   "param1": "val1",  
   "param2": "val2", 
   "funcReference": "someFunctionName", 
   "objName": "valueWithoutQuotes" 
} 

发布为答案,因为我无法在评论中发布代码

于 2012-09-24T07:37:52.067 回答