How do I get formatted JSON in .NET using C#?(如何使用 C# 在 .NET 中获取格式化的 JSON?)
问题描述
我正在使用 .NET JSON 解析器,并希望序列化我的配置文件,使其可读.所以而不是:
I am using .NET JSON parser and would like to serialize my config file so it is readable. So instead of:
{"blah":"v", "blah2":"v2"}
我想要更好的东西,比如:
I would like something nicer like:
{
    "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 完成这个.
You are going to have a hard time accomplishing this with JavaScriptSerializer.
试试 JSON.Net.
对 JSON.Net 示例稍作修改
With minor modifications from JSON.Net example
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"
}
文档:序列化对象
Documentation: Serialize an Object
这篇关于如何使用 C# 在 .NET 中获取格式化的 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 C# 在 .NET 中获取格式化的 JSON?
				
        
 
            
        基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
 - 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
 - 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
 - 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
 - 首先创建代码,多对多,关联表中的附加字段 2022-01-01
 - JSON.NET 中基于属性的类型解析 2022-01-01
 - 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
 - 如何动态获取文本框中datagridview列的总和 2022-01-01
 - 全局 ASAX - 获取服务器名称 2022-01-01
 - 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				