forked from CFPAOrg/Minecraft-Mod-Language-Package
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonFormatter.cs
88 lines (79 loc) · 3.03 KB
/
JsonFormatter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Text.Unicode;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace Language.Core
{
public sealed class JsonFormatter
{
private readonly StreamReader _reader;
private readonly StreamWriter _writer;
private readonly string _modName;
public JsonFormatter(StreamReader reader, StreamWriter writer, string modName)
{
_reader = reader;
_writer = writer;
_modName = modName;
}
public void Format()
{
var builder = new StringBuilder();
while (!_reader.EndOfStream)
{
builder.AppendLine(_reader.ReadLine());
}
_reader.BaseStream.Seek(0, SeekOrigin.Begin);
try
{
if (string.IsNullOrEmpty(builder.ToString()))
{
throw new NullReferenceException();
}
if (string.IsNullOrWhiteSpace(builder.ToString()))
{
throw new NullReferenceException();
}
//有憨憨作者在json里写除了string以外的内容全部抛出
JsonSerializer.Deserialize<Dictionary<string, string>>(builder.ToString(), new JsonSerializerOptions()
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
var jr = new JsonTextReader(_reader);
var jo = new JObject();
var jt = (JObject)JToken.ReadFrom(jr, new JsonLoadSettings() { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Ignore, CommentHandling = CommentHandling.Ignore });
foreach (var (key, value) in jt)
{
jo.Add(key, value.Value<string>());
}
_writer.Write(jo.ToString());
_writer.Close();
_writer.Dispose();
_reader.Close();
_reader.Dispose();
}
catch
{
if (!Directory.Exists($"{Directory.GetCurrentDirectory()}/broken"))
{
Directory.CreateDirectory($"{Directory.GetCurrentDirectory()}/broken");
}
_writer.Write("{}");
_writer.Close();
_writer.Dispose();
_reader.Close();
_reader.Dispose();
File.WriteAllText($"{Directory.GetCurrentDirectory()}/broken/{_modName}{DateTime.UtcNow.Millisecond}.json", builder.ToString());
}
}
}
}