c# - C# 中的 JSON 格式化程序?

寻找一个函数,该函数将 Json 的 string 作为输入,并使用换行符和缩进对其进行格式化。验证将是一个奖励,但不是必需的,我不需要将其解析为对象或任何东西。

有人知道这样的图书馆吗?


示例输入:

{"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"]}, {"long_name":"New York", "short_name":"New York", "types":[ "administrative_area_level_2", "political"]}, {"long_name":"New York", "short_name":"NY", "types":[ "administrative_area_level_1", "political"]}, {"long_name":"United States", "short_name":"US", "types":[ "country", "political"]}], "geometry":{"location":{"lat":40.7143528, "lng":-74.0059731}, "location_type":"APPROXIMATE", "viewport":{"southwest":{"lat":40.5788964, "lng":-74.2620919}, "northeast":{"lat":40.8495342, "lng":-73.7498543}}, "bounds":{"southwest":{"lat":40.4773990, "lng":-74.2590900}, "northeast":{"lat":40.9175770, "lng":-73.7002720}}}}]} 

最佳答案

您也可以使用 Newtonsoft.Json为此库并使用 Formatting.Indented 枚举调用 SerializeObject -

var x = JsonConvert.SerializeObject(jsonString, Formatting.Indented);

文档: Serialize an Object


更新-

刚刚又试了一次。很确定这曾经有效 - 也许它在后续版本中发生了变化,或者我只是在想象一些事情。无论如何,根据下面的评论,它并没有按预期工作。但是,这些确实如此(刚刚在 linqpad 中测试过)。第一个来自评论,第二个是我在 SO 其他地方找到的示例 -

void Main()
{
    //Example 1
    var t = "{\"x\":57,\"y\":57.0,\"z\":\"Yes\"}";
    var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(t); 
    var f = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(f);

    //Example 2
    JToken jt = JToken.Parse(t);
    string formatted = jt.ToString(Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(formatted);

    //Example 2 in one line -
    Console.WriteLine(JToken.Parse(t).ToString(Newtonsoft.Json.Formatting.Indented));
}

https://stackoverflow.com/questions/4580397/

相关文章:

java - 如何打印格式化的 BigDecimal 值?

java - 强制点 (".")作为java中的小数分隔符

html - Bootstrap 3.0 : How to have text and input

python - Pandas :设置编号。最大行数

javascript - AngularJS 格式 JSON 字符串输出

c# - 如何将 Visual Studio 设置为使用 K&R 样式包围?

vim - 如何让 Vim 的 `J` 和 `gq` 命令在一段时间后使用一个空格?

html - 是否可以在 Dreamweaver 中自动格式化您的代码?

python - 将 Python 字符串格式化与列表一起使用

java - Intellij 代码格式化,Java 新行注解