简体   繁体   中英

How to deserialize in C# an unknown JSON string to some Object

I need to parse in C# (key ,value wise) a string that is built in a JSON format (to be exact I need to parse the binding parameter of Knockout data-bind). I go over the html file and I extract the bindings. I want to modify each and every binding (string-wise), but It's really hard for me to parse the string, since I can't really know where each binding stops and the other starts.

for example:

data-bind="text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"

will result in the following string:

"text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"

I want to modify the string in the following way:

newString= "text('gggg'),event(mouseover(x=function(){alert(1);return 'd,y'}))"

I figured out that the best way to do it is to deserialize the string by JSON and then it will be easier for me to get access to each and every binding element. I write at C#, but since I go over the html file and each data-bind is different and can contain different amount and type of attributes I would like to have a general object that I can deserialize to. I checked out DataContractJsonSerializer but I don't see how it solves my problem. Can you please suggest me what's best for my case? Mary

You can do it with something like this:

var obj = ko.bindingProvider.instance.getBindings(yourDomElement,
                                                ko.contextFor(yourDomElement));
alert(JSON.stringify(obj));

And then do whatever you want with obj.

Fiddle

But... well... don't!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM