Skip to content

Instantly share code, notes, and snippets.

@dominsights
Created September 2, 2020 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dominsights/668c6df3f79fb69e53f780437b576814 to your computer and use it in GitHub Desktop.
Save dominsights/668c6df3f79fb69e53f780437b576814 to your computer and use it in GitHub Desktop.
Solution JsonConverter
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace JsonConverter
{
/*
* Nowadays it's important to know how to work with JSON, in this exercise candidate must convert a HTTP query string into JSON
#######################################################
Input: name=john&name=smith&age=30&city=chicago&married=true
#######################################################
Output: {"name":["john","smith"],"age": 30,"city":"chicago","married":true}
*/
class Program
{
static void Main(string[] args)
{
var result = Solution("name=john&name=smith&age=30&city=chicago&married=true");
Console.WriteLine(result);
Console.ReadKey();
}
private static string Solution(string query)
{
var dictionary = new Dictionary<string, List<Token>>();
string[] querySplit = query.Split('&');
foreach(string split in querySplit)
{
string[] keyValue = split.Split('=');
string key = keyValue[0];
string value = keyValue[1];
if(dictionary.ContainsKey(key))
{
dictionary[key].Add(new Token(value));
} else
{
dictionary.Add(key, new List<Token> { new Token(value) });
}
}
StringBuilder sb = new StringBuilder();
sb.Append('{');
for(int i = 0; i < dictionary.Count; i++)
{
var keyValue = dictionary.ElementAt(i);
sb.Append('\"' + keyValue.Key + '\"' + ":");
int size = keyValue.Value.Count;
if(size > 1) // if element is array
{
sb.Append("[");
for(int j = 0; j < size; j++)
{
var token = keyValue.Value[j];
sb.Append(token);
bool isNotLastToken = j + 1 != size;
if (isNotLastToken)
{
sb.Append(",");
}
}
sb.Append("]");
} else // if element is a field
{
sb.Append(keyValue.Value.First());
}
bool isNotLastKeyValue = i + 1 != dictionary.Count;
if (isNotLastKeyValue)
{
sb.Append(",");
}
}
sb.Append('}');
return sb.ToString();
}
}
class Token
{
private string _value;
public Token(string value)
{
_value = value;
}
public override string ToString()
{
if(bool.TryParse(_value, out _))
{
return _value;
} else if(int.TryParse(_value, out _))
{
return _value;
} else
{
return '\"' + _value + '\"';
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment