コンテンツにスキップ

Json.NET

GitHub - JamesNK/Newtonsoft.Json: Json.NET is a popular high-performance JSON framework for .NET

1
> dotnet add package Newtonsoft.Json

JSON パース

input.json
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
{
  "name": "Sample Script",
  "parameters": [
    {
      "type": "file",
      "name": "FileName",
      "value": "FileValue",
      "description": "FileDescription"
    },
    {
      "type": "files",
      "name": "FilesName",
      "value": ["FilesValue1", "FilesValue2", "FilesValue3"],
      "description": "FilesDescription"
    }
  ]
}
ScriptDefinition.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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace App
{
    public class InvalidScriptDefinitionException : Exception
    {
        public InvalidScriptDefinitionException(string message) : base(message) { }
    }

    public record ScriptDefinition
    {
        [JsonProperty("name")]
        public string Name { get; }

        [JsonProperty("description")]
        public string Description { get; }

        [JsonProperty("parameters")]
        public IScriptParameter[] Parameters { get; }

        public ScriptDefinition(string name, string description, IScriptParameter[] parameters)
        {
            Name = name;
            Description = description;
            Parameters = parameters;
        }

        public static ScriptDefinition FromJson(string json)
        {
            JObject obj = JObject.Parse(json);
            string name = obj["name"]?.Value<string>() ?? "";
            string description = obj["description"]?.Value<string>() ?? "";
            var ps = obj["parameters"]?.Value<JArray>() ?? [];
            var parameters = ps.Select<JToken, IScriptParameter>(parameter =>
            {
                var type = parameter["type"]?.Value<string>();
                if (type is null)
                {
                    throw new InvalidScriptDefinitionException($"The attribute \"type\" is required in the following JSON:{Environment.NewLine}{obj}");
                }
                if (type == "file")
                {
                    return ScriptParameterFile.FromJson(parameter.ToString());
                }
                else if (type == "files")
                {
                    return ScriptParameterFiles.FromJson(parameter.ToString());
                }
                throw new InvalidScriptDefinitionException($"Unknown type in the following JSON:{Environment.NewLine}{obj}");
            }).ToArray();
            return new ScriptDefinition(name, description, parameters);
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }
    }

    public interface IScriptParameter
    {
        string Name { get; }
        string Description { get; }
        string ToJson();
    }

    public record ScriptParameterFile : IScriptParameter
    {
        [JsonProperty("name")]
        public string Name { get; }

        [JsonProperty("description")]
        public string Description { get; }

        [JsonProperty("value")]
        public string Value { get; }

        public ScriptParameterFile(string name, string description, string value)
        {
            Name = name;
            Description = description;
            Value = value;
        }

        public static ScriptParameterFile FromJson(string json)
        {
            JObject obj = JObject.Parse(json);
            string name = obj["name"]?.Value<string>() ?? "";
            string description = obj["description"]?.Value<string>() ?? "";
            string value = obj["value"]?.Value<string>() ?? "";
            return new ScriptParameterFile(name, description, value);
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }
    }
    public record ScriptParameterFiles : IScriptParameter
    {
        [JsonProperty("name")]
        public string Name { get; }

        [JsonProperty("description")]
        public string Description { get; }

        [JsonProperty("value")]
        public string[] Value { get; }

        public ScriptParameterFiles(string name, string description, string[] value)
        {
            Name = name;
            Description = description;
            Value = value;
        }

        public static ScriptParameterFiles FromJson(string json)
        {
            JObject obj = JObject.Parse(json);
            string name = obj["name"]?.Value<string>() ?? "";
            string description = obj["description"]?.Value<string>() ?? "";
            string[] value = obj["value"]?.ToObject<string[]>() ?? [];
            return new ScriptParameterFiles(name, description, value);
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }
    }
}
Program.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
namespace App
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var json = File.ReadAllText("input.json");
            var scriptDefinition = ScriptDefinition.FromJson(json);
            Console.WriteLine(scriptDefinition);
            Console.WriteLine(scriptDefinition.ToJson());
        }
    }
}