fix null handling in keybind list parsing (#744)

This commit is contained in:
Jesse Plamondon-Willard 2021-01-20 01:22:29 -05:00
parent 587d60495e
commit 48f6857892
No known key found for this signature in database
GPG Key ID: CF8B1456B3E29F49
1 changed files with 25 additions and 32 deletions

View File

@ -40,27 +40,34 @@ namespace StardewModdingAPI.Framework.Serialization
{ {
string path = reader.Path; string path = reader.Path;
// validate JSON type switch (reader.TokenType)
if (reader.TokenType != JsonToken.String)
throw new SParseException($"Can't parse {nameof(KeybindList)} from {reader.TokenType} node (path: {reader.Path}).");
// parse raw value
string str = JToken.Load(reader).Value<string>();
if (objectType == typeof(Keybind))
{ {
return Keybind.TryParse(str, out Keybind parsed, out string[] errors) case JsonToken.Null:
? parsed return objectType == typeof(Keybind)
: throw new SParseException($"Can't parse {nameof(Keybind)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}"); ? new Keybind()
} : new KeybindList();
if (objectType == typeof(KeybindList)) case JsonToken.String:
{ {
return KeybindList.TryParse(str, out KeybindList parsed, out string[] errors) string str = JToken.Load(reader).Value<string>();
? parsed
: throw new SParseException($"Can't parse {nameof(KeybindList)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}");
}
throw new SParseException($"Can't parse unexpected type {objectType} from {reader.TokenType} node (path: {reader.Path})."); if (objectType == typeof(Keybind))
{
return Keybind.TryParse(str, out Keybind parsed, out string[] errors)
? parsed
: throw new SParseException($"Can't parse {nameof(Keybind)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}");
}
else
{
return KeybindList.TryParse(str, out KeybindList parsed, out string[] errors)
? parsed
: throw new SParseException($"Can't parse {nameof(KeybindList)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}");
}
}
default:
throw new SParseException($"Can't parse {objectType} from unexpected {reader.TokenType} node (path: {reader.Path}).");
}
} }
/// <summary>Writes the JSON representation of the object.</summary> /// <summary>Writes the JSON representation of the object.</summary>
@ -71,19 +78,5 @@ namespace StardewModdingAPI.Framework.Serialization
{ {
writer.WriteValue(value?.ToString()); writer.WriteValue(value?.ToString());
} }
/*********
** Private methods
*********/
/// <summary>Read a JSON string.</summary>
/// <param name="str">The JSON string value.</param>
/// <param name="path">The path to the current JSON node.</param>
protected KeybindList ReadString(string str, string path)
{
return KeybindList.TryParse(str, out KeybindList parsed, out string[] errors)
? parsed
: throw new SParseException($"Can't parse {nameof(KeybindList)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}");
}
} }
} }