首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何美化JSON以便在TextBox中显示?

如何美化JSON以便在TextBox中显示?
EN

Stack Overflow用户
提问于 2011-05-31 00:15:59
回答 3查看 71.6K关注 0票数 53

如何用C#美化JSON?我想在TextBox控件中打印结果。

是否可以使用JavaScriptSerializer,或者我应该使用JSON.net?除非迫不得已,否则我希望避免对字符串进行反序列化。

EN

回答 3

Stack Overflow用户

发布于 2015-04-13 01:26:12

使用JSON.Net,您可以使用特定的格式来美化输出。

Demo on dotnetfiddle。

代码

public class Product
{
    public string Name {get; set;}
    public DateTime Expiry {get; set;}
    public string[] Sizes {get; set;}
}

public void Main()
{
    Product product = new Product();
    product.Name = "Apple";
    product.Expiry = new DateTime(2008, 12, 28);
    product.Sizes = new string[] { "Small" };

    string json = JsonConvert.SerializeObject(product, Formatting.None);
    Console.WriteLine(json);
    json = JsonConvert.SerializeObject(product, Formatting.Indented);
    Console.WriteLine(json);
}

输出

{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
{
  "Name": "Apple",
  "Expiry": "2008-12-28T00:00:00",
  "Sizes": [
    "Small"
  ]
}
票数 46
EN

Stack Overflow用户

发布于 2021-03-12 01:54:00

您可以在不使用新的System.Text.Json名称空间反序列化的情况下处理JSON,以避免添加对json.NET的依赖。

using System.IO;
using System.Text;
using System.Text.Json;

public static string BeautifyJson(string json)
{
    using JsonDocument document = JsonDocument.Parse(json);
    using var stream = new MemoryStream();
    using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions() { Indented = true });
    document.WriteTo(writer);
    writer.Flush();
    return Encoding.UTF8.GetString(stream.ToArray());
}

The docs have more examples of how to use the low-level types in the namespace.

票数 3
EN

Stack Overflow用户

发布于 2020-03-18 21:57:24

ShouldSerializeContractResolver.cs

public class ShouldSerializeContractResolver : DefaultContractResolver
    {
        public static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            return property;
        }
    }
 var beautifyJson= Newtonsoft.Json.JsonConvert.SerializeObject(data, new JsonSerializerSettings()
            {
                ContractResolver = ShouldSerializeContractResolver.Instance,
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.Indented
            });

你可以用上面的代码美化json。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6178544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档