我有一个JSON string
我需要让它变得更好C#
。我尝试了这里的代码:
JSON formatter in C#?
这是我在项目中使用的一个类:
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);
}
}
}
在我的页面中,我有这段代码可以调用该类并在屏幕上写一个字符串。
IRestResponse response5 = GetCampaigns();
string formattedJason = JsonHelper.FormatJson(response5.Content.ToString());
Response.Write(formattedJason);
我的问题是格式化的 Json 没有换行符,所以它是这样的:
{ "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 } ] }
我怎样才能获得更好的 Json,例如:
{
"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"
]
},