Skip to content

Commit 005873e

Browse files
committed
\#160 - accept JSON and original file names in parser
1 parent c2c238c commit 005873e

File tree

3 files changed

+9
-14
lines changed

3 files changed

+9
-14
lines changed

core/shared/src/main/scala/scalapb_circe/JsonFormat.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,8 @@ class Parser(
278278

279279
val valueMap: Map[FieldDescriptor, PValue] = (for {
280280
fd <- cmp.scalaDescriptor.fields
281-
jsValue <- values.get(serializedName(fd)) if !jsValue.isNull
281+
jsValue <- values.get(ScalapbJsonCommon.jsonName(fd)).orElse(values.get(fd.asProto.getName))
282+
if !jsValue.isNull
282283
} yield (fd, parseValue(fd, jsValue))).toMap
283284

284285
PMessage(valueMap)
@@ -331,6 +332,7 @@ class Parser(
331332
}
332333

333334
object JsonFormat {
335+
334336
import com.google.protobuf.wrappers
335337
import scalapb_json.ScalapbJsonCommon._
336338

core/shared/src/test/scala/scalapb_circe/CodecSpec.scala

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -76,19 +76,6 @@ class CodecSpec extends AnyFreeSpec with Matchers {
7676
// Using asJson with an implicit printer includes the default value.
7777
g.asJson mustBe Json.obj("numberOfStrings" -> Json.fromInt(0))
7878
}
79-
80-
"decode using an implicit parser w/ non-standard settings" in {
81-
implicit val parser: Parser = new Parser(preservingProtoFieldNames = true)
82-
83-
// Use the snake-case naming to define a Guitar Json object.
84-
val j = Json.obj("number_of_strings" -> Json.fromInt(42))
85-
86-
// Using the regular JsonFormat parser decodes to the defaultInstance.
87-
JsonFormat.fromJson[Guitar](j) mustBe Guitar.defaultInstance
88-
89-
// Using as[T] with an implicit parser decodes back to the original value (42).
90-
j.as[Guitar] mustBe Right(Guitar(42))
91-
}
9279
}
9380

9481
"GeneratedEnum" - {

core/shared/src/test/scala/scalapb_circe/JsonFormatSpec.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,12 @@ class JsonFormatSpec extends AnyFlatSpec with Matchers with OptionValues {
338338
new Parser().fromJsonString[MyTest]("""{"optEnum":2}""") must be(MyTest(optEnum = Some(MyEnum.V2)))
339339
}
340340

341+
342+
"TestProto" should "parse original field names" in {
343+
new Parser().fromJsonString[MyTest]("""{"opt_enum":1}""") must be(MyTest(optEnum = Some(MyEnum.V1)))
344+
new Parser().fromJsonString[MyTest]("""{"opt_enum":2}""") must be(MyTest(optEnum = Some(MyEnum.V2)))
345+
}
346+
341347
"PreservedTestJson" should "be TestProto when parsed from json" in {
342348
new Parser(preservingProtoFieldNames = true).fromJsonString[MyTest](PreservedTestJson) must be(TestProto)
343349
}

0 commit comments

Comments
 (0)