LoginSignup
9
9

More than 5 years have passed since last update.

[Unity][C#]LitJsonでint型からlong型への変換でエラーになるときの対処法

Last updated at Posted at 2014-10-03

前提

UnityでJsonを扱うのにLitJsonを使っています。

エラー

int型の数値を、long型へ変換する際にLitJsonはエラーになるようです。
実際にやってるのは以下のようなコードです。

test.cs
class Player : JsonData
{
    public int    player_id;
    public string player_name;
    public long   player_exp;
}
string json   = "{\"player_id\":1,\"player_name\":\"tnnsst35\",\"player_exp\":100}";
// JsonException: Can't assign value '100' (type System.Int32) to type System.Int64
Player player = JsonMapper.ToObject<Player>(json);
Debug.Log(player.player_name);

player_expの値はint型で扱える100ですが、player_expはlong型でしか扱えない値になる場合があるため、long型に変換する必要があります。
コードを実行してみると、LitJsonのJsonMapper.ToObjectで「JsonException: Can't assign value '100' (type System.Int32) to type System.Int64(訳:int型の値'100'をlong型に代入できないよ)」というエラーになってしまいます。

対処法

LitJsonの仕様(バグ?)らしいので、LitJsonを直接修正してしまいます。
修正するファイルは「LitJson/JsonMapper.cs」です。

JsonMapper.cs
// 私の手元にあるJsonMapper.csでは次の行は323行目です。
if (reader.Token == JsonToken.Double ||
    reader.Token == JsonToken.Int ||
    reader.Token == JsonToken.Long ||
    reader.Token == JsonToken.String ||
    reader.Token == JsonToken.Boolean) {

    Type json_type = reader.Value.GetType ();

    // 以下の4行を追加
    if (inst_type == typeof(long) &&
        json_type == typeof(int)) {
        json_type = typeof(long);
    }

    if (inst_type.IsAssignableFrom (json_type))
        return reader.Value;

    // If there's a custom importer that fits, use it
// 以下省略

4行追加しています。

inst_typeは変換後の型、json_typeは変換前の型ですね。
変換後はlong型で、変換前はint型であるならば、変換前をlong型として扱うようにするという感じです。

今のところ他への影響もなく快適に動いています。

9
9
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
9
9