Search code examples
c#algorithmserializationjson.netdeserialization

How to serialize and deserialize json in c #


I am using an API that returns json data. I have found Newtonsoft JSON, but I didn't find docs for how to use.

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}    

Solution

  • For syntax and documentation go here.

    This is is a variation of what I used in a school project

    using Newtonsoft.Json;
    
    public static string ConvertObjectToJson<T>(T Ls)
    {
        if (Ls == null)
            return null;
    
        return JsonConvert.SerializeObject(Ls);
    }
    
    public static T JasonConvertToObj<T>(string JsonStr , T FalseReturn)
    {
        try
        {
            return JsonConvert.DeserializeObject<T>(JsonStr);
        }
        catch (Exception e)
        {
            string erorstr = e.Message;
            return FalseReturn;
        }
    }