LoginSignup
4
4

More than 5 years have passed since last update.

Jil で enum を含むオブジェクトを Deserialize する

Last updated at Posted at 2016-01-21

Jil で enum を含むオブジェクトを Deserialize する

enum 型を含むオブジェクトを Jil でデシリアライズすると失敗します。
この対処を示します。

情報源は次です。
Deserialisation w/ CamelCase exception #167

確認したコード

public enum RoundMethod
{
    Unknown,
    なし,
    切り上げ,
    切り捨て,
    四捨五入,
}

public class Unit
{
    public string Name { get; set; }
    public RoundMethod Round { get; set; }
}

class Jil9
{
    static void Main()
    {
        var json = "{\"業務\":{\"Round\":2,\"Name\":\"kg\"}}";

        IDictionary<string, Unit> dic;
        try
        {
            dic = Jil.JSON.Deserialize<IDictionary<string, Unit>>(json);

            foreach (var d in dic)
                Console.WriteLine($"{d.Key}: {d.Value.Name}, {d.Value.Round}");
        }
        catch (DeserializationException e)
        {
            var logmessage = $"Message: {e.Message}, SnippetAfterError: {e.SnippetAfterError}, Source: {json}\n";
            Console.WriteLine(logmessage);
        }

        Console.ReadKey();
    }
}

上記の Deserialize は失敗し、例外 e は次のように出力されます。

Message: Expected character: '"', SnippetAfterError: ,"Name":"kg"}}, Unit: {"業務":{"Round":2,"Name":"kg"}}

この問題は、型定義に JilDirective 属性をつけることで、期待どおり enum RoundMethod 型の要素としてデシリアライズしてるようになりました。

public class Unit
{
    public string Name { get; set; }

    [JilDirective(TreatEnumerationAs=typeof(int))]
    public RoundMethod Round { get; set; }
}

次の出力を得ます。

業務: kg, 切り上げ

確認した環境

  • Windows 10 Home 64 ビット
  • Visual Studio Community 2015 Update 1
  • Jil 2.12.1
4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4