234 .net c# json javascriptserializer
我正在使用.NET JSON解析器,并希望序列化我的配置文件,以便它是可读的.所以代替:
{"blah":"v", "blah2":"v2"}
Run Code Online (Sandbox Code Playgroud)
我想要更好的东西:
{
"blah":"v",
"blah2":"v2"
}
Run Code Online (Sandbox Code Playgroud)
我的代码是这样的:
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();
}
Run Code Online (Sandbox Code Playgroud)
Sky*_*ers 241
使用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; }
}
}
Run Code Online (Sandbox Code Playgroud)
结果
{
"Sizes": [
"Small",
"Medium",
"Large"
],
"Price": 3.99,
"Expiry": "\/Date(1230447600000-0700)\/",
"Name": "Apple"
}
Run Code Online (Sandbox Code Playgroud)
文档:序列化对象
dvd*_*dmn 160
Json.Net库的简短示例代码
private static string FormatJson(string json)
{
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
Run Code Online (Sandbox Code Playgroud)
Dun*_*art 121
如果你有一个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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
ash*_*ber 89
用于美化现有JSON的最短版本:(编辑:使用JSON.net)
JToken.Parse("mystring").ToString()
Run Code Online (Sandbox Code Playgroud)
输入:
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
Run Code Online (Sandbox Code Playgroud)
输出:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
要漂亮地打印一个对象:
JToken.FromObject(myObject).ToString()
Run Code Online (Sandbox Code Playgroud)
Dar*_*usz 36
Oneliner使用Newtonsoft.Json.Linq:
string prettyJson = JToken.Parse(uglyJsonString).ToString(Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)
Ebu*_*ube 31
所有这些都可以在一个简单的行中完成:
string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)
Ome*_*r K 26
对于那些问我如何使用 C# 在 .NET 中获取格式化 JSON 并希望立即了解如何使用它的人以及单行爱好者。以下是缩进的 JSON 字符串一行代码:
有 2 个众所周知的 JSON 格式化程序或解析器可供序列化:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(yourObj, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)
using System.Text.Json;
var jsonString = JsonSerializer.Serialize(yourObj, new JsonSerializerOptions { WriteIndented = true });
Run Code Online (Sandbox Code Playgroud)
And*_*erd 18
这是使用 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());
}
Run Code Online (Sandbox Code Playgroud)
Mak*_*man 11
您可以使用以下标准方法来获取格式化的Json
JsonReaderWriterFactory.CreateJsonWriter(Stream stream,Encoding encoding,bool ownsStream,bool indent,string indentChars)
只设置"indent == true"
尝试这样的事情
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());
}
}
Run Code Online (Sandbox Code Playgroud)
注意线条
var currentCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
....
Thread.CurrentThread.CurrentCulture = currentCulture;
Run Code Online (Sandbox Code Playgroud)
在具有不同区域设置的计算机上进行反序列化时,应使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
har*_*eyt 11
netcoreapp3.1
var js = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
WriteIndented = true
});
Run Code Online (Sandbox Code Playgroud)
使用System.Text.Json集JsonSerializerOptions.WriteIndented = true:
JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize<Type>(object, options);
Run Code Online (Sandbox Code Playgroud)
using System.Text.Json;
...
var parsedJson = JsonSerializer.Deserialize<ExpandoObject>(json);
var options = new JsonSerializerOptions() { WriteIndented = true };
return JsonSerializer.Serialize(parsedJson, options);
Run Code Online (Sandbox Code Playgroud)