Page 1 of 2

JSON Serializer/Deserializer Extension for CSHTML5

Posted: Sat Jun 11, 2016 8:20 am
by JS-Support @Userware
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Tue Aug 16, 2016 9:00 am
by JS-Support @Userware
UPDATE: the JSON extension has just been updated to support Enums.

Regards,
JS-Support

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Thu Oct 27, 2016 7:54 am
by boonec6
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?

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Thu Oct 27, 2016 12:36 pm
by boonec6
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?

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Thu Feb 16, 2017 6:01 am
by Amrutha
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Mon Apr 10, 2017 8:33 am
by JS-Support @Userware
UPDATE: the JSON extension has just been updated to support DateTime!.

Regards,
JS-Support

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Thu Jun 08, 2017 7:06 am
by JS-Support @Userware
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Tue Jun 20, 2017 6:05 am
by JS-Support @Userware
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Fri Jul 14, 2017 8:12 am
by JS-Support @Userware
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Wed Sep 13, 2017 1:09 am
by JS-Support @Userware
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Fri Oct 13, 2017 7:00 am
by JS-Support @Userware
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Thu Dec 21, 2017 1:05 pm
by stan0611
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Thu Dec 21, 2017 1:57 pm
by stan0611
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[]'.

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Wed May 02, 2018 7:48 am
by JS-Support @Userware
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

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Wed Sep 12, 2018 4:31 am
by JS-Support @Userware
UPDATE: The JSON extension has just been updated with the following feature:
- Improved support for Long types (Int64)

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Fri Nov 09, 2018 9:31 am
by JS-Support @Userware
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)

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Wed Jul 17, 2019 10:37 am
by TaterJuice
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.

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Fri Jul 19, 2019 3:02 am
by JS-Support @Userware
Thank you @TaterJuice!

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Fri Jul 17, 2020 4:55 am
by fangeles
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.

Re: JSON Serializer/Deserializer Extension for CSHTML5

Posted: Sun Jul 19, 2020 5:46 am
by JS-Support @Userware
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.