Share via


Converting Data to JSON in .NET Framework 3.5

Thanks to Scottguā€™s blog (https://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx) from where I got this idea to write this blog.

I used System.Runtime.Serialization.DataContractJsonSerializer class for serialiazing the data into JSON format instead of System.Web.Script.Serialization.JavaScriptSerializer which is now obselete (can still be used).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Web.Script.Serialization;
using System.Runtime.Serialization;
using System.IO;

namespace JSONConverter {

    class Program {
        static void Main(string[] args) {
            List<Person> people = new List<Person> {
                new Person {ID=1, FirstName="Vijay", LastName="Pathak"},
                new Person {ID=2, FirstName="John", LastName="Smith"}
            };
            people.ConvertToJSON();
        }
    }

    /* The DataContractAttribute type is required and must be applied to the class whose data is
     * going to serialized.
     * DataMemberAttribute is applicable for the fields which are being serialized
     */
    [DataContract]

    public class Person {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
    }

    public static class JsonSerializerClass {
        public static void ConvertToJSON(this object obj) {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            FileStream objStream = new FileStream("D:\\JSONString.txt", FileMode.Open);
            serializer.WriteObject(objStream, obj);
            objStream.Close();
        }
    }

The output of the JSONString.txt will look like this

[{"FirstName":"Vijay","ID":1,"LastName":"Pathak"},{"FirstName":"John","ID":2,"LastName":"Smith"}]

Comments