我正在使用.NET JSON解析器,并希望序列化我的配置文件,使其可读。所以而不是:
{"blah":"v", "blah2":"v2"}
我想要更好的东西:
{
"blah":"v",
"blah2":"v2"
}
我的代码是这样的:
using System.Web.Script.Serialization;
var ser = new JavaScriptSerializer();
configSz = ser.Serialize(config);
using (var f = (TextWriter)File.CreateText(configFn))
{
f.WriteLine(configSz);
f.Close();
}
答案 0 :(得分:217)
使用JavaScriptSerializer,您将很难完成此任务。
尝试JSON.Net。
通过JSON.Net示例的微小修改
using System;
using Newtonsoft.Json;
namespace JsonPrettyPrint
{
internal class Program
{
private static void Main(string[] args)
{
Product product = new Product
{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Price = 3.99M,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
Console.WriteLine(json);
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
}
}
internal class Product
{
public String[] Sizes { get; set; }
public decimal Price { get; set; }
public DateTime Expiry { get; set; }
public string Name { get; set; }
}
}
结果
{
"Sizes": [
"Small",
"Medium",
"Large"
],
"Price": 3.99,
"Expiry": "\/Date(1230447600000-0700)\/",
"Name": "Apple"
}
答案 1 :(得分:146)
Json.Net库的简短示例代码
private static string FormatJson(string json)
{
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
答案 2 :(得分:110)
如果你有一个JSON字符串并想要“美化”它,但又不想将它序列化为一个已知的C#类型,那么下面的技巧就是这个(使用JSON.NET):
using System;
using System.IO;
using Newtonsoft.Json;
class JsonUtil
{
public static string JsonPrettify(string json)
{
using (var stringReader = new StringReader(json))
using (var stringWriter = new StringWriter())
{
var jsonReader = new JsonTextReader(stringReader);
var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
jsonWriter.WriteToken(jsonReader);
return stringWriter.ToString();
}
}
}
答案 3 :(得分:71)
最短版本美化现有JSON:(编辑:使用JSON.net)
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
输入:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
输出:
JToken.FromObject(myObject).ToString()
漂亮打印对象:
{{1}}
答案 4 :(得分:23)
Oneliner使用Newtonsoft.Json
:
string prettyJson = JToken.Parse(uglyJsonString).ToString(Formatting.Indented);
答案 5 :(得分:19)
所有这些操作都可以在一行中完成:
string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);
答案 6 :(得分:12)
以下是使用Microsoft的System.Text.Json库的解决方案:
static string FormatJsonText(string jsonString)
{
using var doc = JsonDocument.Parse(
jsonString,
new JsonDocumentOptions
{
AllowTrailingCommas = true
}
);
MemoryStream memoryStream = new MemoryStream();
using (
var utf8JsonWriter = new Utf8JsonWriter(
memoryStream,
new JsonWriterOptions
{
Indented = true
}
)
)
{
doc.WriteTo(utf8JsonWriter);
}
return new System.Text.UTF8Encoding()
.GetString(memoryStream.ToArray());
}
答案 7 :(得分:7)
您可以使用以下标准方法获取格式化的Json
JsonReaderWriterFactory.CreateJsonWriter(Stream stream,Encoding encoding,bool ownsStream,bool indent,string indentChars)
仅设置&#34;缩进== true&#34;
尝试这样的事情
public readonly DataContractJsonSerializerSettings Settings =
new DataContractJsonSerializerSettings
{ UseSimpleDictionaryFormat = true };
public void Keep<TValue>(TValue item, string path)
{
try
{
using (var stream = File.Open(path, FileMode.Create))
{
var currentCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
try
{
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(
stream, Encoding.UTF8, true, true, " "))
{
var serializer = new DataContractJsonSerializer(type, Settings);
serializer.WriteObject(writer, item);
writer.Flush();
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.ToString());
}
finally
{
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.ToString());
}
}
注意线条
var currentCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
....
Thread.CurrentThread.CurrentCulture = currentCulture;
您应该使用 InvariantCulture 来避免在具有不同区域设置的计算机上进行反序列化时出现异常。例如, double 或 DateTime 的无效格式有时会导致它们。
用于反序列化
public TValue Revive<TValue>(string path, params object[] constructorArgs)
{
try
{
using (var stream = File.OpenRead(path))
{
var currentCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
try
{
var serializer = new DataContractJsonSerializer(type, Settings);
var item = (TValue) serializer.ReadObject(stream);
if (Equals(item, null)) throw new Exception();
return item;
}
catch (Exception exception)
{
Debug.WriteLine(exception.ToString());
return (TValue) Activator.CreateInstance(type, constructorArgs);
}
finally
{
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
}
catch
{
return (TValue) Activator.CreateInstance(typeof (TValue), constructorArgs);
}
}
谢谢!
答案 8 :(得分:6)
netcoreapp3.1
var js = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
WriteIndented = true
});
答案 9 :(得分:3)
使用System.Text.Json
集JsonSerializerOptions.WriteIndented = true
:
JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize<Type>(object, options);
答案 10 :(得分:2)
首先,我想在Duncan Smart帖子下添加评论,但遗憾的是我还没有足够的声誉留下评论。所以我会在这里试一试。
我只想警告副作用。
JsonTextReader在内部将json解析为类型化的JTokens,然后将它们序列化。
例如,如果您的原始JSON是
{ "double":0.00002, "date":"\/Date(1198908717056)\/"}
美化后,你得到了
{
"double":2E-05,
"date": "2007-12-29T06:11:57.056Z"
}
当然两个json字符串都是等效的,并且会反序列化为结构上相等的对象,但是如果你需要保留原始的字符串值,你需要把它变成concideration
答案 11 :(得分:0)
这对我有用。如果有人正在寻找VB.NET版本。
@imports System
@imports System.IO
@imports Newtonsoft.Json
Public Shared Function JsonPrettify(ByVal json As String) As String
Using stringReader = New StringReader(json)
Using stringWriter = New StringWriter()
Dim jsonReader = New JsonTextReader(stringReader)
Dim jsonWriter = New JsonTextWriter(stringWriter) With {
.Formatting = Formatting.Indented
}
jsonWriter.WriteToken(jsonReader)
Return stringWriter.ToString()
End Using
End Using
End Function
答案 12 :(得分:0)
以下代码对我有用:
JsonConvert.SerializeObject(JToken.Parse(yourobj.ToString()))
答案 13 :(得分:0)
对于使用.NET Core 3.1的UTF8编码的JSON文件,我终于能够根据Microsoft提供的以下信息使用JsonDocument:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#utf8jsonreader-utf8jsonwriter-and-jsondocument
string allLinesAsOneString = string.Empty;
string [] lines = File.ReadAllLines(filename, Encoding.UTF8);
foreach(var line in lines)
allLinesAsOneString += line;
JsonDocument jd = JsonDocument.Parse(Encoding.UTF8.GetBytes(allLinesAsOneString));
var writer = new Utf8JsonWriter(Console.OpenStandardOutput(), new JsonWriterOptions
{
Indented = true
});
JsonElement root = jd.RootElement;
if( root.ValueKind == JsonValueKind.Object )
{
writer.WriteStartObject();
}
foreach (var jp in root.EnumerateObject())
jp.WriteTo(writer);
writer.WriteEndObject();
writer.Flush();
答案 14 :(得分:0)
我有一些非常简单的方法。您可以将任何要转换为 json 格式的对象作为输入:
private static string GetJson<T> (T json)
{
return JsonConvert.SerializeObject(json, Formatting.Indented);
}