如何使用 Json.NET 阅读带有评论的 JSON 内容?

7

本文介绍了如何使用 Json.NET 阅读带有评论的 JSON 内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

为了在 Google Chrome 浏览器中安装外部扩展,我尝试更新 Chrome 外部扩展 JSON 文件.使用 Json.NET 似乎很容易:

In order to install an external extension into Google Chrome browser, I try to update a Chrome external extension JSON file. Using Json.NET it seems to be easy:

string fileName = "..."; // Path to a Chrome external extension JSON file

string externalExtensionsJson = File.ReadAllText(fileName);

JObject externalExtensions = JObject.Parse(externalExtensionsJson);


但我得到一个 Newtonsoft.Json.JsonReaderException 说:

"Error parsing comment. Expected: *, got /. Path '', line 1, position 1."


在调用 JObject.Parse 时,因为该文件包含:


when calling JObject.Parse because this file contains:

// This JSON file will contain a list of extensions that will be included
// in the installer.

{
}

并且评论不是 JSON 的一部分(如 如何在 Json.NET 输出中添加注释?).

And comments are not part of JSON (as seen in How do I add comments to Json.NET output?).

我知道我可以使用正则表达式删除评论 (正则表达式删除 JavaScript 双斜杠 (//) 样式的注释),但我需要在修改后将 JSON 重写到文件中,保留注释可能是一件好事.

I know I can remove comments with a regular expression (Regular expression to remove JavaScript double slash (//) style comments), but I need to rewrite JSON into the file after modification and keeping comment can be a good thing.

有没有办法在不删除评论的情况下读取带有评论的 JSON 内容并能够重写它们?

Is there a way to read JSON content with comments without removing them and be able to rewrite them?

推荐答案

Json.NET 只支持读取多行 JavaScript 注释,即/*commment */

Json.NET only supports reading multi-line JavaScript comments, i.e. /* commment */

更新:Json.NET 6.0 支持单行注释

Update: Json.NET 6.0 supports single line comments

这篇关于如何使用 Json.NET 阅读带有评论的 JSON 内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14