Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Self Constructing Objects with JavaScriptSerializer (JSON.PARSE equivalent)

I'm creating a flexible framework for creating and storing settings for third party developers.

One of the better choices we made was to create a system where the developers created their own settings with JSON, and simply serialized the objects later.

I.E.

public class YammerConfig
{
    public string yammerClientId { get; set; }
    public string yammerNetwork { get; set; }

    public YammerConfig(string js)
    {
        var ser = new JavaScriptSerializer();
        var sam = ser.Deserialize<YammerConfig>(js);
        yammerClientId = sam.yammerClientId;
        yammerNetwork = sam.yammerNetwork;
    }
}

This has been an effective way to store settings in a database without having to reconfigure new tables for unique sets of information.

I would love to take this one step further, the way JavaScript itself does, and create objects on the fly that don't need to be manually serialized.

Is it possible to create the equivalent of json.parse in .NET C#?

like image 883
Wesley Avatar asked Sep 20 '26 19:09

Wesley


1 Answers

Why you don't use extention method

For example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Stackoverflow.Helpers
{
    public static class JsonHelper
    {
        private static JavaScriptSerializer ser = new JavaScriptSerializer();
        public static T ToJSON<T>(this string js) where T : class
        {
            return ser.Deserialize<T>(js);
        }

        public static string JsonToString(this object obj)
        {
            return ser.Serialize(obj);
        }
    }
}

easy to use

//Deserialize
string s = "{yammerClientId = \"1\",yammerNetwork = \"2\"}";    
YammerConfig data = s.ToJSON<YammerConfig>();

//Serialize
string de = data.JsonToString();
like image 170
İbrahim Özbölük Avatar answered Sep 23 '26 08:09

İbrahim Özbölük



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!