是否可以将 json 格式的文本转换为字符串而不会出现错误?(C#)

Is it possible to convert text that's in json format to a string without giving errors? (C#)

提问人:imsocontigo 提问时间:2/2/2021 最后编辑:imsocontigo 更新时间:2/2/2021 访问量:153

问:

在我的 C# 程序中,我想创建一个以 json 格式编写的字符串,因此它包含一堆引号,太多了,我无法手动浏览和修复。

那么有没有办法将所有“”固定在一个字符串中并阻止它们轻易出错呢?

string shopJson = "{ "refreshIntervalHrs": 1, "dailyPurchaseHrs": 24, "expiration": "9999-12-31T23:59:59.999Z", "storefronts": [ { "name": "BRStandaloneStorefront", "catalogEntries": [] }

C# JSON 字符串 引号

评论

2赞 TheGeneral 2/2/2021
显示代码和 json,我们无法调试故事
0赞 Jonesopolis 2/2/2021
查找和替换,也许使用正则表达式
0赞 imsocontigo 2/2/2021
我编辑了帖子以显示您想要的内容@00110001
1赞 TheGeneral 2/2/2021
所以,你通常不会自己编写 json,你通常从类/记录/结构/匿名类型序列化它。这样您就不必担心报价和其他讨厌的问题
1赞 Vijay 2/2/2021
我认为您需要序列化数据..使用很少的库

答:

1赞 Josh 2/2/2021 #1

因此,最佳做法是使用像 newtonjsoft 这样的库并创建一个类,然后序列化到该类中。 示例如下:

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
  //{
  //  "Name": "Apple",
 //  "ExpiryDate": "2008-12-28T00:00:00",
 //  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

如果您有您期望的 JSON 字符串,则可以使用在线帮助工具在此处进行转换:https://quicktype.io/csharp/

在 Visual Studio 中,可以使用类文件中的特殊粘贴功能创建类,这是一个过程,因此这里也有一个关于如何执行此操作的链接: https://www.c-sharpcorner.com/article/how-to-paste-json-as-classes-or-xml-as-classes-in-visual-stu/

你的 JSON 应该是:

 { "refreshIntervalHrs": 1, "dailyPurchaseHrs": 24, "expiration": "9999-12- 
   31T23:59:59.999Z", "storefronts": [ { "name": "BRStandaloneStorefront", 
   "catalogEntries": [] }]}

班级会是这样的:

 public class SomeClassName
{
    [JsonProperty("refreshIntervalHrs")]
    public long RefreshIntervalHrs { get; set; }

    [JsonProperty("dailyPurchaseHrs")]
    public long DailyPurchaseHrs { get; set; }

    [JsonProperty("expiration")]
    public DateTimeOffset Expiration { get; set; }

    [JsonProperty("storefronts")]
    public Storefront[] Storefronts { get; set; }
}

public partial class Storefront
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("catalogEntries")]
    public object[] CatalogEntries { get; set; }
}

评论

0赞 Hans Kesting 2/2/2021
您可以指示 Newtonsoft 序列化程序使用 camelCasing,这样您就不需要向每个属性添加属性