Friday, May 23, 2014

how to remove white space in the json create.

When I create json after hitting my api the json that is generated has got lot of blank spaces in it . how can I remove those blank/white spaces. For example :
{"JsonGenerated":[{  "Developers": [    {      "Dev1d": 16247,      "DevSortorder": 0,      "DevLocationId": 0,      "devName": "Tony  Matric",      "DevLAstName": null}]
This is just a sample json the actual json is really quite big in size with many nodes.  I just  download this json and use later. So nothing related to UI of javasript.
Also I cant replace  all the spaces within this string with empty because there can we values of these nodes which require space for example in the above json I will never want to concatenate TonyMatric.
Final output that I want is :
{"JsonGenerated":[{"Developers": [{"Dev1d": 16247,"DevSortorder": 0,"DevLocationId": 0,"devName": "Tony  Matric","DevLAstName": null}]}]}



Solution :
   public string RemoveWhiteSpace(string jsonstring)
        {
            package =
jsonstring.Replace("\r\n", "");
            var text =
jsonstring.Replace("/\n/g", " ").Replace("/\r/g", " ");
            string[] t = null;
            StringBuilder str1 = new StringBuilder();
            char check = 'A';
            var inString = false;
            for (int i = 0, len = text.Length; i < len; i++)
            {
                string c = text[i].ToString();
                if (inString & check == Convert.ToChar(c))
                {
                    if (text[i - 1] != '\\')
                    {
                        inString = false;
                    }
                }
                else if (!inString && (c == "\"" || c == "'"))
                {
                    inString = true;
                    check = Convert.ToChar(c);
                }
                else if (!inString && (c == " " || c == "\t" || c == "\r" || c == "\n"))
                {
                    c = "";
                }
                str1.Append(c);
            }

            return str1.ToString();
        }