如何美化JSON以显示在TextBox中? [英] How can I beautify JSON for display in a TextBox?

查看:209
本文介绍了如何美化JSON以显示在TextBox中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I beautify JSON with C#? I want to print the result in a TextBox control.

是否可以为此使用JavaScriptSerializer,还是应该使用JSON.net?除非需要,否则我想避免反序列化字符串.

Is it possible to use JavaScriptSerializer for this, or should I use JSON.net? Unless I have to, I'd like to avoid deserializing the string.

推荐答案

使用 JSON.Net ,您可以使用特定格式.

With JSON.Net you can beautify the output with a specific formatting.

演示.

代码

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"
  ]
}

这篇关于如何美化JSON以显示在TextBox中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆