Quantcast
Channel: User Max - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Serialize unquoted property values

$
0
0

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!


Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>