Vic*_*tor 3 json .net-core asp.net-core system.text.json
我正在处理大型 JSON,其中一些元素包含以 Base 64 编码的大型(最多 100MB)文件。例如:
{ "name": "One Name", "fileContent": "...base64..." }
Run Code Online (Sandbox Code Playgroud)
我想将 fileContent 属性值存储在磁盘中(以字节形式)并将其替换为文件的路径,如下所示:
{ "name": "One Name", "fileRoute": "/route/to/file" }
Run Code Online (Sandbox Code Playgroud)
是否可以使用流或任何其他方式通过 System.Text.Json 来实现此目的,以避免在内存中使用非常大的 JSON?
您的基本要求是将包含属性的 JSON 转换为"fileContent": "...base64...","fileRoute": "/route/to/file"同时还将 out 的值fileContent写入单独的二进制文件,而不将 的值具体化为fileContent完整的字符串。
目前尚不清楚这是否可以通过 .NET Core 3.1 实现来完成System.Text.Json。即使可以,也绝非易事。Utf8JsonReader简单地从a 生成aStream需要工作,请参阅使用 .NET core 3.0/System.text.Json 解析 JSON 文件。完成此操作后,有一种方法Utf8JsonReader.ValueSequence可以将最后处理的令牌的原始值作为ReadOnlySequence<byte>输入有效负载的一部分返回。然而,该方法似乎并不容易使用,因为它仅当令牌包含在多个段中时才有效,不保证值的格式良好,并且不会转义 JSON 转义序列。
Newtonsoft 在这里根本不起作用,因为它JsonTextReader总是完全具体化每个原始字符串值。
作为替代方案,您可以考虑由 . 返回的读者和作者JsonReaderWriterFactory。这些读取器和写入器在读取和写入JSON 时被使用DataContractJsonSerializer并即时将其转换为 XML 。由于这些读取器和写入器的基类是和,因此它们支持通过 读取块中的字符串值。更好的是,它们支持通过 读取块中的 Base64 二进制值。 XmlReaderXmlWriterXmlReader.ReadValueChunk(Char[], Int32, Int32)XmlReader.ReadContentAsBase64(Byte[], Int32, Int32)
给定这些读取器和写入器,我们可以使用流式转换算法将fileContent节点转换为fileRoute节点,同时将 Base64 二进制文件提取到单独的二进制文件中。
首先,介绍以下 XML 流式转换方法,该方法大致基于Mark Fussell的Combining the XmlReader and XmlWriter Classes for simple Streaming Transforms以及Automating Replaceing Tables from external files 的答案:
public static class XmlWriterExtensions
{
// Adapted from this answer /sf/answers/2023244051/
// to /sf/ask/2022400831/
// By /sf/users/262092771/
/// <summary>
/// Make a DEEP copy of the current xmlreader node to xmlwriter, allowing the caller to transform selected elements.
/// </summary>
/// <param name="writer"></param>
/// <param name="reader"></param>
/// <param name="shouldTransform"></param>
/// <param name="transform"></param>
public static void WriteTransformedNode(this XmlWriter writer, XmlReader reader, Predicate<XmlReader> shouldTransform, Action<XmlReader, XmlWriter> transform)
{
if (reader == null || writer == null || shouldTransform == null || transform == null)
throw new ArgumentNullException();
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
if (reader.NodeType == XmlNodeType.Element && shouldTransform(reader))
{
using (var subReader = reader.ReadSubtree())
{
transform(subReader, writer);
}
// ReadSubtree() places us at the end of the current element, so we need to move to the next node.
reader.Read();
}
else
{
writer.WriteShallowNode(reader);
}
}
while (!reader.EOF && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
/// <summary>
/// Make a SHALLOW copy of the current xmlreader node to xmlwriter, and advance the XML reader past the current node.
/// </summary>
/// <param name="writer"></param>
/// <param name="reader"></param>
public static void WriteShallowNode(this XmlWriter writer, XmlReader reader)
{
// Adapted from https://learn.microsoft.com/en-us/archive/blogs/mfussell/combining-the-xmlreader-and-xmlwriter-classes-for-simple-streaming-transformations
// By Mark Fussell https://learn.microsoft.com/en-us/archive/blogs/mfussell/
// and rewritten to avoid using reader.Value, which fully materializes the text value of a node.
if (reader == null)
throw new ArgumentNullException("reader");
if (writer == null)
throw new ArgumentNullException("writer");
switch (reader.NodeType)
{
case XmlNodeType.None:
// This is returned by the System.Xml.XmlReader if a Read method has not been called.
reader.Read();
break;
case XmlNodeType.Element:
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, true);
if (reader.IsEmptyElement)
{
writer.WriteEndElement();
}
reader.Read();
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.EntityReference:
case XmlNodeType.DocumentType:
case XmlNodeType.Comment:
//Avoid using reader.Value as this will fully materialize the string value of the node. Use WriteNode instead,
// it copies text values in chunks. See: https://referencesource.microsoft.com/#system.xml/System/Xml/Core/XmlWriter.cs,368
writer.WriteNode(reader, true);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
reader.Read();
break;
default:
throw new XmlException(string.Format("Unknown NodeType {0}", reader.NodeType));
}
}
}
public static partial class XmlReaderExtensions
{
// Taken from this answer /sf/answers/3789532561/
// To /sf/ask/3788868121/
// By /sf/users/262092771/
public static bool CopyBase64ElementContentsToFile(this XmlReader reader, string path)
{
using (var stream = File.Create(path))
{
byte[] buffer = new byte[8192];
int readBytes = 0;
while ((readBytes = reader.ReadElementContentAsBase64(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, readBytes);
}
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,使用JsonReaderWriterFactory引入以下方法从一个 JSON 文件流式传输到另一个 JSON 文件,并fileContent根据需要重写节点:
public static class JsonPatchExtensions
{
public static string[] PatchFileContentToFileRoute(string oldJsonFileName, string newJsonFileName, FilenameGenerator generator)
{
var newNames = new List<string>();
using (var inStream = File.OpenRead(oldJsonFileName))
using (var outStream = File.Open(newJsonFileName, FileMode.Create))
using (var xmlReader = JsonReaderWriterFactory.CreateJsonReader(inStream, XmlDictionaryReaderQuotas.Max))
using (var xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(outStream))
{
xmlWriter.WriteTransformedNode(xmlReader,
r => r.LocalName == "fileContent" && r.NamespaceURI == "",
(r, w) =>
{
r.MoveToContent();
var name = generator.GenerateNewName();
r.CopyBase64ElementContentsToFile(name);
w.WriteStartElement("fileRoute", "");
w.WriteAttributeString("type", "string");
w.WriteString(name);
w.WriteEndElement();
newNames.Add(name);
});
}
return newNames.ToArray();
}
}
public abstract class FilenameGenerator
{
public abstract string GenerateNewName();
}
// Replace the following with whatever algorithm you need to generate unique binary file names.
public class IncrementalFilenameGenerator : FilenameGenerator
{
readonly string prefix;
readonly string extension;
int count = 0;
public IncrementalFilenameGenerator(string prefix, string extension)
{
this.prefix = prefix;
this.extension = extension;
}
public override string GenerateNewName()
{
var newName = Path.ChangeExtension(prefix + (++count).ToString(), extension);
return newName;
}
}
Run Code Online (Sandbox Code Playgroud)
然后调用如下:
var binaryFileNames = JsonPatchExtensions.PatchFileContentToFileRoute(
oldJsonFileName,
newJsonFileName,
// Replace the following with your actual binary file name generation algorithm
new IncrementalFilenameGenerator("Question59839437_fileContent_", ".bin"));
Run Code Online (Sandbox Code Playgroud)
资料来源:
演示小提琴在这里。
| 归档时间: |
|
| 查看次数: |
818 次 |
| 最近记录: |