JSON Serializer/Deserializer Extension for CSHTML5

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Sat Jun 11, 2016 8:20 am

Dear CSHTML5 users,

We are pleased to inform you that we have released an open-source extension for CSHTML5 that adds JSON serialization/deserialization support!


If you are new to the concept of Extensions for CSHTML5, you can read more here.


UPDATE (January 21, 2021): Fixed NotSupportedException with generic enumerables during deserialization in the Simulator (with CSHTML5 v2), and Enum deserialization
UPDATE (February 26, 2020): Fixed serialization on Integer types when running in the Simulator (with CSHTML5 v2)
UPDATE (November 9, 2018): Added Bridge.NET support, added a bunch of stubs, and changed namespace from "CSHTML5.Extensions.Json" to "Newtonsoft.Json"
UPDATE (September 12, 2018): Improved support for Long types (Int64)
UPDATE (October 13, 2017): Added support for case-insensitive deserialization: if the case-sensitive property is not found, the deserializer looks for the case-insensitive property. Also added JsonArray object with ability to count the number of items.
UPDATE (September 13, 2017): Fixed an issue with static properties that interfered with the serialization/deserialization. Furthermore, private properties are no longer serialized by default. To serialize them, add "BindingFlags.NonPublic" to the "GetProperties" call.
UPDATE (July 14, 2017): Improved support for numbers and booleans that are surrounded by quotes. Improved support for generic list deserialization.
UPDATE (June 20, 2017): Added support for Guid, null, Nullable<>, and ObservableCollection. Improved support for collections and enumerables.
UPDATE (June 8, 2017): Fixed issue with deserialization of empty arrays.
UPDATE (April 2017): Added support for Enum and DateTime.


How to install/use it?

To install and use it, simply add a new class named "JsonConvert.cs" to your project, and copy/paste the code from the following URL:

https://gist.github.com/cshtml5/2446871a8bc0fa4ceddcfb448b6aca54


Documentation:

Here is an example code for Serialization:

Code: Select all

string json = JsonConvert.SerializeObject(product);

MessageBox.Show(json);



Here is an example code for strongly-typed Deserialization:

Code: Select all

Product deserializedProduct = await JsonConvert.DeserializeObject<Product>(json);

MessageBox.Show("Name of the second feature: " + deserializedProduct.Features[1].Name);
MessageBox.Show("Name of the third available size: " + deserializedProduct.Sizes[2]);
MessageBox.Show("Release date: " + deserializedProduct.ReleaseDate.ToString());



And here is an example code for dynamic Deserialization:

Code: Select all

IJsonType deserializedObject = await JsonConvert.DeserializeObject(json);

MessageBox.Show("Product name: " + deserializedObject["Name"].Value.ToString());
MessageBox.Show("Name of the second feature: " + deserializedObject["Features"][1]["Name"].Value.ToString());
MessageBox.Show("Name of the third available size: " + deserializedObject["Sizes"][2].Value.ToString());



Here is some JSON string for testing:

Code: Select all


    "Name":"TestProduct",
    "ProductType":"B2C",
    "Price":12.5,
    "Count":341,
    "IsAvailable":true,
    "Sizes":[ 
        "Small",
        "Medium",
        "Large"
    ],
    "Features":[ 
        { 
            "Name":"TestFeature1"
        },
        { 
            "Name":"TestFeature2"
        },
        { 
            "Name":"TestFeature3"
        }
    ],
    "ReleaseDate":"2017-04-10T16:26:41.754Z"
}



Here are some test classes:

Code: Select all

public class Product
{
    public string Name { get; set; }
    public ProductType ProductType { get; set; }
    public double Price { get; set; }
    public int Count { get; set; }
    public bool IsAvailable { get; set; }
    public string[] Sizes { get; set; }
    public List<Feature> Features { get; set; }
    public DateTime ReleaseDate { get; set; }
}

public class Feature
{
    public string Name { get; set; }
}

public enum ProductType
{
    B2B, B2C
}



We hope you will enjoy this library!

If you find any issues, please feel free to post them on the forums or to send an email to support@cshtml5.com

Thank you.
Regards,
The CSHTML5 Team

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Tue Aug 16, 2016 9:00 am

UPDATE: the JSON extension has just been updated to support Enums.

Regards,
JS-Support

boonec6
Posts: 6
Joined: Thu Dec 10, 2015 8:38 am

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby boonec6 » Thu Oct 27, 2016 7:54 am

Sorry if this is a ridiculous question - I've got limited programming knowledge that I tend to gather just as I need it. I have been using C# to make web service call and deserialize the JSON through JSON.Net, but that's obviously not possible with C#/XAML. The web service I'm working with uses spaces in field names, so with JSON.Net I was able to set the "JsonProperty" in the classes:

Code: Select all

        public class CustomFields
        {
            [JsonProperty("Est. GP % (Number Only)")]
            public string estgppcnt { get; set; }
        }
           


Is there a similar functionality with this extension?

boonec6
Posts: 6
Joined: Thu Dec 10, 2015 8:38 am

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby boonec6 » Thu Oct 27, 2016 12:36 pm

I think I came up with a workaround (admittedly, not a good one) by doing

Code: Select all

response = response.Replace("Est. GP % (Number Only)", "estgppcnt");


But now I'm running into the issue that the deserialization breaks if there are null values. Is there a way to get around that?

Amrutha
Posts: 21
Joined: Tue Nov 15, 2016 5:10 am

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby Amrutha » Thu Feb 16, 2017 6:01 am

Dear Team,

The extension file to convet to json 'JSONConverter' does not support DateTime conversion.

Kindly let us know if the file will support the DateTime conversion to json in future.

Thanks & Regards,
Amrutha

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Mon Apr 10, 2017 8:33 am

UPDATE: the JSON extension has just been updated to support DateTime!.

Regards,
JS-Support

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Thu Jun 08, 2017 7:06 am

UPDATE: the JSON extension has just been updated with a fix to an issue that prevented deserialization of empty arrays (such as in the following JSON: { myarray:[] } ).

Regards,
JS-Support

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Tue Jun 20, 2017 6:05 am

UPDATE: The JSON extension has been updated with the following features:
- Support for Guid
- Support for null and Nullable<>
- Support for ObservableCollection
- Improved support for collections and enumerables

Regards,
JS-Support

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Fri Jul 14, 2017 8:12 am

UPDATE: The JSON extension has been updated today with the following features:
- Improved support for numbers and booleans that are surrounded by quotes.
- Improved support for generic list deserialization.

Regards,
JS-Support

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Wed Sep 13, 2017 1:09 am

UPDATE: The JSON extension has just been updated with the following features:
- Fixed an issue with static properties that interfered with the serialization/deserialization.
- Private properties are no longer serialized by default. To serialize them, add "BindingFlags.NonPublic" to the "GetProperties" call.

Regards,
JS-Support

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Fri Oct 13, 2017 7:00 am

UPDATE: The JSON extension has just been updated with the following features:
- Added support for case-insensitive deserialization: if the case-sensitive property is not found, the deserializer looks for the case-insensitive property.
- Added JsonArray object with ability to count the number of items.

Regards,
JS-Support

stan0611
Posts: 2
Joined: Thu Dec 21, 2017 1:01 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby stan0611 » Thu Dec 21, 2017 1:05 pm

Hi,

I'm trying to deserialize an array of custom objects. However, the result is the same object on every place in the array. It somehow puts the last object in the serialized array on all place on the deserialized array.

I'm not doing anything exotic I think. I will test with the given examples if I can reproduce this issue.

Has anyone else noticed this issue?

Stan

stan0611
Posts: 2
Joined: Thu Dec 21, 2017 1:01 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby stan0611 » Thu Dec 21, 2017 1:57 pm

Also,

Why does this code not work:

Code: Select all

 
      Product p = new Product();
       p.Count = 12;
             p.Features = new List<Feature>() { new Feature() { Name = "feat1" }, new Feature() { Name = "feat2" } };
                p.IsAvailable = true;
                p.Name = "product 1";
                p.Price = 1.99;
                p.ProductType = ProductType.B2B;
                p.ReleaseDate = DateTime.Now;
                p.Sizes = new string[2] { "Big", "Small" };
                string serialized = JsonConvert.SerializeObject(p);
                Product deserialized = await JsonConvert.DeserializeObject<Product>(serialized);
 


I get the following error:

A first chance exception of type 'System.InvalidOperationException' occurred in TestCshtml5WCF.dll
Additional information: Cannot convert a string to 'System.String[]'.

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Wed May 02, 2018 7:48 am

stan0611 wrote:I get the following error: A first chance exception of type 'System.InvalidOperationException' occurred in TestCshtml5WCF.dll Additional information: Cannot convert a string to 'System.String[]'.

stan0611 wrote:the result is the same object on every place in the array. It somehow puts the last object in the serialized array on all place on the deserialized array.


Thanks for reporting this issue.

It has now been fixed in CSHTML5 v1.1.2, which will be available before the end of the week.

Regards,
JS-Support

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Wed Sep 12, 2018 4:31 am

UPDATE: The JSON extension has just been updated with the following feature:
- Improved support for Long types (Int64)

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Fri Nov 09, 2018 9:31 am

UPDATE: The JSON extension has just been updated with the following changes:
- Added Bridge.NET support
- Changed namespace from "CSHTML5.Extensions.Json" to "Newtonsoft.Json"
- Added "Required" enum, "NullValueHandling" enum, and JsonProperty stub (not functional)

TaterJuice
Posts: 147
Joined: Thu Mar 16, 2017 5:40 am
Contact:

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby TaterJuice » Wed Jul 17, 2019 10:37 am

It's a little messy, but I added support for JsonIgnore attribute

Code: Select all

public class JsonIgnoreAttribute : Attribute
{
   //superfluous...
}


Then replace the following method in the original JsonConvert class

Code: Select all

#region Private Methods
static object ConvertCSharpObjectToJavaScriptObject(object cSharpObject, bool ignoreErrors)
{
   if (cSharpObject is Enum || cSharpObject is Guid || cSharpObject is long)
   {
      return cSharpObject.ToString();
   }
   else if (cSharpObject is DateTime)
   {
      //Uncomment when fully supported by CSHTML5:
      //return ((DateTime)cSharpObject).ToUniversalTime().ToString("s", System.Globalization.CultureInfo.InvariantCulture);

      var dateTimeUtc = ((DateTime)cSharpObject).ToUniversalTime();
      TimeSpan timeSince1970 = (dateTimeUtc - new DateTime(1970, 1, 1, 0, 0, 0));
      double millisecondsSince1970 = timeSince1970.TotalMilliseconds;
      var jsDate = Interop.ExecuteJavaScript("new Date($0)", millisecondsSince1970);
      string json = Convert.ToString(Interop.ExecuteJavaScript("$0.toJSON()", jsDate));
      return json;
   }
   else if (cSharpObject is string
#if !BRIDGE
         || (cSharpObject != null && cSharpObject.GetType().IsValueType)
#endif
      )
   {
      return cSharpObject;
   }
#if BRIDGE
   else if (cSharpObject != null && cSharpObject.GetType().IsValueType)
   {
      return Interop.ExecuteJavaScript("$0.v", cSharpObject);
   }
#endif
   else if (cSharpObject is IEnumerable && !(cSharpObject is string))
   {
      //----------------
      // ARRAY
      //----------------

      // Create the JS array:
      var jsArray = Interop.ExecuteJavaScript("[]");

      // Traverse the enumerable:
      foreach (var cSharpItem in (IEnumerable)cSharpObject)
      {
         var jsItem = ConvertCSharpObjectToJavaScriptObject(cSharpItem, ignoreErrors);
         Interop.ExecuteJavaScript("$0.push($1)", jsArray, jsItem);
      }

      return jsArray;
   }
   else if (cSharpObject != null)
   {
      //----------------
      // OBJECT
      //----------------

      var jsObject = Interop.ExecuteJavaScript(@"new Object()");

      // Traverse all properties:
      foreach (PropertyInfo property in cSharpObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
      {
         string propertyName = property.Name;
         object propertyValue = property.GetValue(cSharpObject);

         if (propertyValue != null)
         {
            bool ignoreProperty = false;
            var attrs = property.GetCustomAttributes(false);
            if (attrs != null)
            {
               foreach (object attr in attrs)
               {
                  if (attr is JsonIgnoreAttribute ignoreAttribute)
                  {
                     ignoreProperty = true;
                  }
               }
            }
            if(!ignoreProperty)
            {
               var recursionResult = ConvertCSharpObjectToJavaScriptObject(propertyValue, ignoreErrors);
               if (recursionResult != null)
               {
                  Interop.ExecuteJavaScript(@"$0[$1] = $2;", jsObject, propertyName, recursionResult);
               }
            }
         }
      }

      return jsObject;
   }
   else
      return Interop.ExecuteJavaScript("undefined");
}


It currently only works on properties, not class declarations, and does not support inheritance.

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Fri Jul 19, 2019 3:02 am

Thank you @TaterJuice!

fangeles
Posts: 52
Joined: Wed Jan 16, 2019 12:48 am

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby fangeles » Fri Jul 17, 2020 4:55 am

I tried to copy-paste the JsonConvert code but the code editor gives me this error

The type or namespace name 'ArrayList' could not be found (are you missing a using directive or an assembly reference?



I am using the Bridge version 2.0.0-alpha63-83

Hoping for your reply.

Thanks.

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: JSON Serializer/Deserializer Extension for CSHTML5

Postby JS-Support @Userware » Sun Jul 19, 2020 5:46 am

fangeles wrote:I tried to copy-paste the JsonConvert code but the code editor gives me this error
The type or namespace name 'ArrayList' could not be found (are you missing a using directive or an assembly reference?

I am using the Bridge version 2.0.0-alpha63-83


To fix this, please add the "BRIDGE" compiler directive (aka "compilation symbol") to your project. To do so, go to your project properties, go to the "Build" tab and add BRIDGE to the compilation symbols.

Alternatively, simply add #define BRIDGE to the top of the JsonConvert.cs class.


Return to “Extensions and Plugins for CSHTML5”

Who is online

Users browsing this forum: No registered users and 1 guest