From 4d117ba98b8bd8b84c079ee963a8f43d6605328c Mon Sep 17 00:00:00 2001 From: Will Richardson Date: Sat, 5 Aug 2023 08:45:13 +0000 Subject: [PATCH] Fix error message when parsing unknown JSON enum value `#string_value` can be the value of the next token, which results in a confusing error message. --- spec/std/json/serialization_spec.cr | 3 +++ src/json/from_json.cr | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/spec/std/json/serialization_spec.cr b/spec/std/json/serialization_spec.cr index 980bc1d65533..4657759481ea 100644 --- a/spec/std/json/serialization_spec.cr +++ b/spec/std/json/serialization_spec.cr @@ -302,6 +302,9 @@ describe "JSON serialization" do expect_raises(JSON::ParseException, %(Unknown enum JSONSpecEnum value: "three")) do JSONSpecEnum.from_json(%("three")) end + expect_raises(JSON::ParseException, %(Unknown enum JSONSpecEnum value: "three")) do + NamedTuple(foo: JSONSpecEnum).from_json(%({"foo": "three", "other": 1})) + end expect_raises(JSON::ParseException, %(Expected String but was Int)) do JSONSpecEnum.from_json(%(1)) end diff --git a/src/json/from_json.cr b/src/json/from_json.cr index bd77199cdc85..fdc18b3a9171 100644 --- a/src/json/from_json.cr +++ b/src/json/from_json.cr @@ -318,11 +318,13 @@ def Enum.new(pull : JSON::PullParser) {% if @type.annotation(Flags) %} value = {{ @type }}::None pull.read_array do - value |= parse?(pull.read_string) || pull.raise "Unknown enum #{self} value: #{pull.string_value.inspect}" + string = pull.read_string + value |= parse?(string) || pull.raise "Unknown enum #{self} value: #{string.inspect}" end value {% else %} - parse?(pull.read_string) || pull.raise "Unknown enum #{self} value: #{pull.string_value.inspect}" + string = pull.read_string + parse?(string) || pull.raise "Unknown enum #{self} value: #{string.inspect}" {% end %} end