locked
How to Convert dictionary to json using three arguments RRS feed

  • Question

  • Today:

    Table
    address 1     zipcode    city
    ------------------------------
    angel         123        and
    candy         321        klj
    mandy         874        jk3

    Goal:

    object
        1
            address: xxxx
            zipcode: xxxx
            city:    xxxxx
        2
            address: xxxx
            zipcode: xxxx
            city:    xxxxx
        3
            address: xxxx
            zipcode: xxxx
            city:    xxxxx

    How do you convert it from dictionary to json using c#?

    In dictionary, you only can have two arguments

        Dictionary<string, string> aa1 = new Dictionary<string, string>();
    
        aa1.Add("angel", "123");
        aa1.Add("candy", "321");
        aa1.Add("mandy", "874");
    
        string myJsonString = (new JavaScriptSerializer()).Serialize(aa1);

    Thank you!

    Friday, January 12, 2018 2:54 PM

All replies

  • You cannot store that table in a dictionary as you have defined. That is the first thing that is wrong. What structure is the data in originally (i.e. DataTable, custom object, etc)?

    For a custom object you can easily serialize the data by simply serializing the values into an array. I would recommend against trying to create an object with numeric values for properties as this is going to be difficult to deserialize.

    class MyData
    {
        [DataMember(Name = "address")]
        public string Address { get; set; }
    
        [DataMember(Name = "zipcode")]
        public string ZipCode { get; set; }
    
        public string City { get; set; }
    }
    
    static void Main ( string[] args )
    {
        var values = new[]
        {
            new MyData() { Address = "angel", ZipCode = "123", City = "and "},
            new MyData() { Address = "candy", ZipCode = "321", City = "klj"},
            new MyData() { Address = "mandy", ZipCode = "874", City = "jk3" }
        };
    
        var serializer = new JavaScriptSerializer();
                
        //Produces an array
        var results = serializer.Serialize(values);
    }

    Note that JavascriptSerializer is not recommend to be used. In the documentation they recommend using JSON.NET or another serializer. There is also the DataContractSerializer which is what most of the framework code uses internally. It does require that you annotate the type.

    Also note that in the above example the serializer will use the exact names of the properties which is atypical for JSON. JSON tends to use camel casing. Other serializers allow you to change this but I don't think JavaScriptSerializer does. If you stick with this serializer then you'll need to adjust the members to serialize what you want.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, January 12, 2018 3:14 PM
  • Here's an example that uses the dictionary object. As Michael said, use another serializer.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Script.Serialization;
    
    namespace ConsoleApplication5
    {
        class Program
        {
            static void Main(string[] args)
            {
                Dictionary<string, person> aa1 = new Dictionary<string, person>();
    
    
                aa1.Add("1", new person { address="Sam", zipcode = "12345", city = "abc" });
                aa1.Add("2", new person { address = "Fred", zipcode = "12356", city = "def" });
                aa1.Add("3", new person { address = "Susan", zipcode = "12367", city = "xyz" });
    
                //aa1.Add("angel", "123");
                //aa1.Add("candy", "321");
                //aa1.Add("mandy", "874");
    
                string myJsonString = (new JavaScriptSerializer()).Serialize(aa1);
    
                Console.WriteLine(myJsonString);
                Console.ReadLine();
            }
        }
    
        class person
        {
            public string address { get; set; }
            public string zipcode { get; set; }
            public string city { get; set; }
        }
    }
    

    The output:

    {
      "1":{"address":"Sam","zipcode":"12345","city":"abc"},
      "2":{"address":"Fred","zipcode":"12356","city":"def"},
      "3":{"address":"Susan","zipcode":"12367","city":"xyz"}
    }


    Mike Smith TechTrainingNotes.blogspot.com
    Books: SharePoint 2007 2010 Customization for the Site Owner, SharePoint 2010 Security for the Site Owner

    Friday, January 12, 2018 3:25 PM
  • "Note that JavascriptSerializer is not recommend to be used."

    Why?

    Friday, January 12, 2018 11:03 PM
  • Microsoft now recommends the Newtonsoft.Json library and includes it in the MVC and other Visual Studio templates. One reason is performance. Another is around date formatting and parsing. JSON does not define a date data type and each parser does its own thing.

    Each JSON serializer will return its own favorite date format. Here are some examples:

    • "\/Date(1489627020170)\/" is a JavaScript serial number for number of milliseconds since January 1, 1970.
    • "\/Date(1489627020170-0500)\/" is the same, but with a time zone adjustment.
    • "2017-03-15T17:46:02.1153043" is the ISO8601 standard with a time zone adjustment.
    • "2017-03-15T17:46:02.1153043-07:00" is the ISO8601 standard with a time zone adjustment.

    The Newtonsoft.Json will map between .NET date times and the date strings created by JavaScript.

    Like most things in the development world, there are multiple options, and the favorites change all the time. Here's one article comparing performance:

    http://www.windward.net/blogs/json-net-really-best-json-serializer-net/

     Scroll down on this page to the feature comparison section: https://www.newtonsoft.com/json


    Mike Smith TechTrainingNotes.blogspot.com
    Books: SharePoint 2007 2010 Customization for the Site Owner, SharePoint 2010 Security for the Site Owner

    Saturday, January 13, 2018 3:50 AM