0

I have a JSON string that I need to make it nicer in C#. I tried the code from here: JSON formatter in C#?

that is a class I used in my project:

class JsonHelper
{
  private const string INDENT_STRING = "    ";
  public static string FormatJson(string str)
  {
    var indent = 0;
    var quoted = false;
    var sb = new StringBuilder();
    for (var i = 0; i < str.Length; i++)
    {
      var ch = str[i];
      switch (ch)
      {
        case '{':
        case '[':
        sb.Append(ch);
        if (!quoted)
        {
        sb.AppendLine();
       Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
        }
        break;
        case '}':
        case ']':
        if (!quoted)
        {
          sb.AppendLine();
       Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
        }
        sb.Append(ch);
        break;
        case '"':
        sb.Append(ch);
        bool escaped = false;
        var index = i;
        while (index > 0 && str[--index] == '\\')
          escaped = !escaped;
        if (!escaped)
          quoted = !quoted;
        break;
        case ',':
        sb.Append(ch);
        if (!quoted)
        {
         sb.AppendLine();
         Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
        }
        break;
        case ':':
        sb.Append(ch);
        if (!quoted)
          sb.Append(" ");
        break;
        default:
        sb.Append(ch);
        break;
      }
    }
    return sb.ToString();
  }
}

static class Extensions
{
  public static void ForEach<T>(this IEnumerable<T> ie, Action<T> action)
  {
    foreach (var i in ie)
    {
      action(i);
    }
  }
}

and in my page I have this code to call the class and write a string on the screen.

IRestResponse response5 = GetCampaigns();  
string formattedJason = JsonHelper.FormatJson(response5.Content.ToString());
Response.Write(formattedJason);

My problem is that the formatted Json doesnt have a line break so it is like this:

 { "total_count": 10, "items": [ { "clicked_count": 2559, "opened_count":     7021, "submitted_count": 3102, "unsubscribed_count": 0, "bounced_count": 4, "id": "3", "name": "Approved Email", "created_at": "Wed, 09 Oct 2013 17:16:35 GMT", "delivered_count": 2984, "complained_count": 0, "dropped_count": 118 }, { "clicked_count": 240, "opened_count": 434, "submitted_count": 183, "unsubscribed_count": 0, "bounced_count": 0, "id": "5", "name": "Ready to Shop", "created_at": "Wed, 09 Oct 2013 00:21:08 GMT", "delivered_count": 181, "complained_count": 0, "dropped_count": 2 } ] } 

How I can get a nicer Json something like:

{
"status" : "OK",
"results" : [
    {
        "types" : [
            "locality",
            "political"
        ],
        "formatted_address" : "New York, NY, USA",
        "address_components" : [
            {
                "long_name" : "New York",
                "short_name" : "New York",
                "types" : [
                    "locality",
                    "political"
                ]
            },
Community
  • 1
  • 1
Alma
  • 3,780
  • 11
  • 42
  • 78
  • 10
    I recommend using [JSON.Net](http://james.newtonking.com/json) for this, it will make your life much easier! – JMK Oct 30 '13 at 16:06
  • 1
    Can't you just add in your formatting code a `'\n'` after `'['`, `'{'`, and `','`? Oh and the closing version of the two parenthesis. – T. Kiley Oct 30 '13 at 16:07
  • I tried to use it I install it from Nuget, but for some reason I am not sure why when I use using Newtonsoft.Json; at the top of the page it gave me this error: "The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)" – Alma Oct 30 '13 at 16:09
  • You can see the ServiceStack.Text(https://github.com/ServiceStack/ServiceStack.Text) project's source code from github. It is the fastest JSON(http://www.servicestack.net/benchmarks/) serializer. – mehmet mecek Oct 30 '13 at 16:10
  • Have you tried to set copy local to true on the Reference? – Jos Vinke Oct 30 '13 at 16:11
  • Sorry Jos Vinke can you explain more about it? – Alma Oct 30 '13 at 16:13
  • You need to add a *reference* to the library. If you are using Visual Studio, right click on the project and "Add Reference". `using` does not add the library to your project. – crashmstr Oct 30 '13 at 16:20
  • @nikoom when using nuget to install a library, it does this on a per-project basis, so make sure you are on the right project. You should not need to add reference as well. – user2586804 Oct 30 '13 at 16:25
  • Best is to right click project and select "`Manage NuGet Packages...`". – user2586804 Oct 30 '13 at 16:26
  • So I can't get the JSON.Net working for this so please stay in my question about the code I sent, what is the problem woth the code that I can't get the line break? – Alma Oct 30 '13 at 16:39

1 Answers1

0

You can just put the text to notepad++ and use JSMin plugin to format the json string. Or JSON.Net is a solution for you.

sblee
  • 86
  • 1
  • 10