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

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!

Related

Can I Deserialize a JSON string that contains 0.0 in C#?

The JSON I'm getting back from a webservice has an integer incorrectly represented as 0.0. My deserialization code looks like this:
var serializer = new JsonSerializer();
var ret = serializer.Deserialize<T>(jsonTextReader);
And I get an error like this:
Input string '0.0' is not a valid integer.
My question is, is there a way to specify a less strict deserialization method so that I can parse this string?
EDIT: The web service returns no schema so I don't know why the deserializer tries to convert it to an int instead of a float or double.
I'd say that you should go ahead and creat your classes on Json -> C#
var o = (JObject)serializer.Deserialize(myjsondata);
You can use the C# dynamic type to make things easier. This technique also makes re-factoring simpler as it does not rely on magic-strings. Use JsonConvert.DeserializeObject<dynamic>()to deserialize this string into a dynamic type then simply access its properties in the usual way in C#.
Im not sure why youre getting
Input string '0.0' is not a valid integer.
since if you dont have any Json data it should just be left at null and you shouldnt have this problem

C# force integer when converting XML to JSON

I am attempting to convert XML into JSON in order to generate a HTTP POST request to an API. I am getting an error because one of the fields is meant to be an integer instead of a string. From what i have read adding "json:Integer="true"" to the node will cause it to become an int, but this doesnt seem to be working for me. Here is the xml and the resulting json. The arrays are working, but the integer is not.
<shipments json:Array="true" xmlns:json="http://james.newtonking.com/projects/json">
<shipment_tracking_number />
<response_shipment_date>2016-10-18T01:00:00.0000000-04:00</response_shipment_date>
<response_shipment_method>UPS Ground</response_shipment_method>
<expected_delivery_date>2016-10-18T01:00:00.0000000-04:00</expected_delivery_date>
<ship_from_zip_code>12345</ship_from_zip_code>
<carrier_pick_up_date>2016-10-18T01:00:00.0000000-04:00</carrier_pick_up_date>
<carrier>UPS</carrier>
<shipment_items json:Array="true">
<shipment_item_id>FF12345K</shipment_item_id>
<alt_shipment_item_id>1234567890</alt_shipment_item_id>
<merchant_sku>B00xxxx</merchant_sku>
<response_shipment_sku_quantity json:Integer="true">1</response_shipment_sku_quantity>
</shipment_items>
</shipments>
string jsonrequest = JsonConvert.SerializeXmlNode(doc,
Newtonsoft.Json.Formatting.None, true);
{"shipments":[
{
"shipment_tracking_number":null,
"response_shipment_date":"2016-10-18T01:00:00.0000000-04:00",
"response_shipment_method":"UPS Ground",
"expected_delivery_date":"2016-10-18T01:00:00.0000000-04:00",
"ship_from_zip_code":"12345",
"carrier_pick_up_date":"2016-10-18T01:00:00.0000000-04:00",
"carrier":"UPS",
"shipment_items":[
{
"shipment_item_id":"FF12345K",
"alt_shipment_item_id":"1234567890",
"merchant_sku":"B00xxxx",
"response_shipment_sku_quantity":"1"
}]
}]
}
I need "response_shipment_sku_quantity":"1" to show up as "response_shipment_sku_quantity":1, but it doesnt seem to be working. I can modify the XML or the code that performs the conversion. I dont mind which as long as this can be done.
You define the attribute wrongly. This is how it should look like.
<response_shipment_sku_quantity json:Type='Integer'>1</response_shipment_sku_quantity>
EDIT:
Newtonsoft.Json XmlNodeConverter
Look methods private void SerializeNode and string dataType = GetDataType(node); they suggest this definition.
Another option is to Deserialize the xml to class with proper types for the properties and after that Serialize it to Json.

Dynamic Json deserialization

Deserialize JSON into C# dynamic object?
Following above question, I copy the dynamicJsonDeserilization and trying to use that in my application.
then I try to access the object as
var Data = json.deserilization(jsonstring);
Now, my string is
{"0":{"Name":"C:\\","Type":"Partition","Path":"C:\\"},"1":{"Name":"D:\\","Type":"Partition","Path":"D:\\"},"2":{"Name":"E:\\","Type":"Partition","Path":"E:\\"}}
i.e. I just have an Array on my server which I convert to JSON string and send.
As per code from best answer I should be able to access it as Data.0 but it give "End of Expression expected", Also Data[0] is giving same error. I am not sure how can I use it ? Any help is appreciated. Thanks.
Now, my string is
{"0":{"Name":"C:\","Type":"Partition","Path":"C:\"},"1":{"Name":"D:\","Type":"Partition","Path":"D:\"},"2":{"Name":"E:\","Type":"Partition","Path":"E:\"}}
Your string is indeed not valid JSON due to escaped quotes.
Those C:\ are breaking the parser. You should generate it like this, sending three backslahes:
{"0":{"Name":"C:\\\","Type":"Partition","Path":"C:\\\"} ...

Is it possible to load Json to a holder object similar to XElement?

The answer to this question shows how to load a Json string to a hard-coded class using JavaScriptSerializer. However, the class structure has to be coded, and this looks impractical if you're just interested in a few values, and not interested in parsing the whole string.
Is there something similar to XElement, where I can simply load a XML string and then use xElement.Elements("Items").Select( el => el.Elements("Title")) in order to list the title of all items, for example. I prefer if I can use pure .NET without third-party libraries. It would be nice if I can also linq it like XElement
In case the context is useful, I'm trying to parse the a list of question provided by StackExchange API (json format) to a nicely formatted string, and I only want some infos like title, link, and author.
It sounds like what you are really asking for is a Linq to JSON adapter. Why be burdened by XML if you don't need to be? JSON is an object serialization format, not an XML format, so you should think of it as "How can I use LINQ to Objects with objects from JSON?
A quick google search for "Linq json" turns up several interesting topics. Give it a spin.

How do I turn a C# Array to XML

I have a basic Generic List that I want turned into XML so I can return it to jquery. What I am trying to do is update my comments section in my article directory. I am returning an array of comment text, comment id, and user name. I would like to turn all of this into an array. Thanks
if (CommentFunctions.AddComment(aid, l.GetUserID(), id, comment))
{
//lets get all the comments for the article
List<CommentType> ct = CommentFunctions.GetCommentsByArticleID(id);
}
As others have pointed out, you'll need to serialize it to convert to XML.
I'd like to mention that if you're trying to return a list of objects to JQuery, that XML isn't the best or easiest format. Have you considered returning JSON?
JavaScriptSerializer serializer = new JavaScriptSerializer();
string JSONText = serializer.Serialize(List<CommentType>);
This will automatically create necessary json to describe your list of CommentTypes. JSON is much easier to parse in javascript and is much smaller to return via HTML.
Plus, you don't need to tell it your field names. It will find them for you and your JSON will be a list of classes just like your CommentType class.
You have to serialize it to XML. There are a number of ways to do this, more or less complex depending on the relative efficiency/speed you need, and the amount of control you need over the XML output.
Have a look here:
http://msdn.microsoft.com/en-us/library/ms950721.aspx
As Robert's comment mentions, you have to serialize the array to XML. Instead of retyping out the answer, however, I would recommend reading this blog post which discusses exactly how you would go about doing that.

Categories