如何使用 C# 从以下节点 json 构建 html

问题描述 投票:0回答:1
{
  "document": {
    "object": "document",
    "data": {
      "schemaVersion": 6
    },
    "nodes": [
      {
        "object": "block",
        "type": "heading-1",
        "isVoid": false,
        "data": {},
        "nodes": [
          {
            "object": "text",
            "leaves": [
              {
                "object": "leaf",
                "text": "Welcome",
                "marks": [],
                "selections": []
              }
            ]
          }
        ]
      },
      {
        "object": "block",
        "type": "paragraph",
        "isVoid": false,
        "data": {},
        "nodes": [
          {
            "object": "text",
            "leaves": [
              {
                "object": "leaf",
                "text": "hello this is impossible",
                "marks": [],
                "selections": []
              }
            ]
          }
        ]
      }
    ]
  }
}

尝试从 gitbook 导出的页面内容构建 html

c# html json html-parsing gitbook
1个回答
0
投票

你没有表现出任何努力,但这对我自己来说是一个有趣的练习,所以你开始吧:

using System.Text.Json;

public static class VeryBasicHtmlRenderer {
    public static StringBuilder AsHtml(this JsonElement el, int indent = 0) => el.GetHtmlNodeType() switch {
        "document" => new StringBuilder()
            .AppendLine("<html>")
            .Append(el.InnerAsHtml("nodes", indent + 2))
            .AppendLine("</html>"),
        "heading-1" => new StringBuilder()
            .Append(' ', indent).AppendLine("<h1>")
            .Append(el.InnerAsHtml("nodes", indent + 2))
            .Append(' ', indent).AppendLine("</h1>"),
        "paragraph" => new StringBuilder()
            .Append(' ', indent).AppendLine("<p>")
            .Append(el.InnerAsHtml("nodes", indent + 2))
            .Append(' ', indent).AppendLine("</p>"),
        "text" => el.InnerAsHtml("leaves", indent),
        "leaf" => new StringBuilder()
            .Append(' ', indent).AppendLine(el.GetProperty("text").GetString()),
        var unknown => throw new NotSupportedException($"Unknown HTML node type '{unknown}'.")
    };
    
    private static StringBuilder InnerAsHtml(this JsonElement el, string prop, int indent) => el
        .GetProperty(prop)
        .EnumerateArray()
        .Aggregate(
            new StringBuilder(),
            (sb, el) => sb.Append(el.AsHtml(indent)));
        
    
    private static string GetHtmlNodeType(this JsonElement el)
        => el.TryGetProperty("type", out var val)
            ? val.GetString()!
            : el.GetProperty("object").GetString()!;
}

用途:

var json = JsonDocument.Parse("""
    {
      "document": {
        "object": "document",
        "data": {
          "schemaVersion": 6
        },
        "nodes": [
          // ...
        ]
      }
    }
    """)
    .RootElement
    .GetProperty("document");
    
var html = json.AsHtml().ToString();

结果:

<html>
  <h1>
    Welcome
  </h1>
  <p>
    hello this is quite possible
  </p>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.