本文介绍了C# 中的 JSON 格式化程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
寻找一个函数,该函数将 Json 的 string
作为输入,并使用换行符和缩进对其进行格式化.验证将是一个奖励,但不是必需的,我不需要将其解析为对象或任何东西.
Looking for a function that will take a string
of Json as input and format it with line breaks and indentations. Validation would be a bonus, but isn't necessary, and I don't need to parse it into an object or anything.
有人知道这样的图书馆吗?
Anyone know of such a library?
示例输入:
{"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}}}}]}
推荐答案
这对我在 .Net Core 3.1 中使用 System.Text.Json 有效
This worked for me using System.Text.Json in .Net Core 3.1
public string PrettyJson(string unPrettyJson)
{
var options = new JsonSerializerOptions(){
WriteIndented = true
};
var jsonElement = JsonSerializer.Deserialize<JsonElement>(unPrettyJson);
return JsonSerializer.Serialize(jsonElement, options);
}
这篇关于C# 中的 JSON 格式化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!