如何在.NET中使用C#获得格式化的JSON?
我正在使用.NET JSONparsing器,并希望序列化我的configuration文件,因此它是可读的。 所以,而不是:
{"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(); }
你将很难用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" }
文档: 序列化对象
Json.Net库的一个较短的示例代码
private static string FormatJson(string json) { dynamic parsedJson = JsonConvert.DeserializeObject(json); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); }
如果你有一个JSONstring,并且想对其进行“美化”,但是不希望将其序列化为已知的C#types,那么下面的方法就是使用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(); } } }
最短的版本来美化现有的JSON:(编辑:使用JSON.net)
JToken.Parse("mystring").ToString()
input:
{"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()
试试Json.Net库来格式化它。
您可以使用以下标准方法获取格式化的Json
JsonReaderWriterFactory.CreateJsonWriter(streamstream,编码编码,布尔ownsStream,布尔缩进,stringindentChars)
只设置“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()); } }
注意线条
var currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; .... Thread.CurrentThread.CurrentCulture = currentCulture;
您应该使用InvariantCulture来避免在具有不同区域设置的计算机上进行反序列化时出现exception。 例如, 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); } }
谢谢!
首先我想在Duncan Smart post下添加评论,但不幸的是,我还没有足够的声望留下评论。 所以我会在这里尝试。
我只是想警告副作用。
JsonTextReader在内部将Jsonparsing为键入的JTokens,然后将它们串行化。
例如,如果你原来的JSON是
{ "double":0.00002, "date":"\/Date(1198908717056)\/"}
美化后,你会得到
{ "double":2E-05, "date": "2007-12-29T06:11:57.056Z" }
当然,这两个jsonstring是等价的,将反序列化到结构上相等的对象,但如果你需要保留原始的string值,你需要把这个进行concideration