定义一个JsonFileParser
public class JsonFileParser
{
private JsonFileParser() { }
public static IDictionary<string, string> Parse(Stream input)
{
return new JsonFileParser().ParseStream(input);
}
private IDictionary<string, string> ParseStream(Stream input)
{
this._data.Clear();
JsonDocumentOptions options = new JsonDocumentOptions
{
AllowTrailingCommas = false,
CommentHandling = JsonCommentHandling.Skip
};
using (var streamReader = new StreamReader(input))
{
using (var jsonDocument = JsonDocument.Parse(streamReader.ReadToEnd(), options))
{
if (jsonDocument.RootElement.ValueKind != JsonValueKind.Object)
{
throw new FormatException("Error_UnsupportedJSONToken");
}
VisitElement(jsonDocument.RootElement);
}
}
return _data;
}
private void VisitElement(JsonElement element)
{
foreach (JsonProperty jsonProperty in element.EnumerateObject())
{
this.EnterContext(jsonProperty.Name);
this.VisitValue(jsonProperty.Value);
this.ExitContext();
}
}
private void VisitValue(JsonElement value)
{
switch (value.ValueKind)
{
case JsonValueKind.Object:
VisitElement(value);
return;
case JsonValueKind.Array:
{
int num = 0;
using(JsonElement.ArrayEnumerator enumerator=value.EnumerateArray().GetEnumerator())
{
while (enumerator.MoveNext())
{
JsonElement value2 = enumerator.Current;
this.EnterContext(num.ToString());
this.VisitValue(value2);
this.ExitContext();
num++;
}
return;
}
break;
}
case JsonValueKind.String:
case JsonValueKind.Number:
case JsonValueKind.True:
case JsonValueKind.False:
case JsonValueKind.Null:
break;
default:
throw new FormatException("Error_UnsupportedJSONToken");
}
string currentPath = this._currentPath;
if (this._data.ContainsKey(currentPath))
{
throw new FormatException("Error_UnsupportedJSONToken");
}
this._data[currentPath] = value.ToString();
}
private void EnterContext(string context)
{
this._context.Push(context);
this._currentPath = ConfigurationPath.Combine(this._context.Reverse<string>());
}
private void ExitContext()
{
this._context.Pop();
this._currentPath = ConfigurationPath.Combine(this._context.Reverse<string>());
}
private readonly IDictionary<string, string> _data = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly Stack<string> _context = new Stack<string>();
private string _currentPath;
}
直接调用Parse方法即可
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
var dic = JsonFileParser.Parse(fileStream);
foreach (KeyValuePair<string, string> keyValuePair in dic)
{
Console.WriteLine($"{keyValuePair.Key}:{keyValuePair.Value}");
}