Skip to content

Commit

Permalink
\#160 - accept JSON and original file names in parser
Browse files Browse the repository at this point in the history
  • Loading branch information
jkobejs committed Oct 25, 2021
1 parent c2c238c commit b955d37
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 14 deletions.
4 changes: 3 additions & 1 deletion core/shared/src/main/scala/scalapb_circe/JsonFormat.scala
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,8 @@ class Parser(

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

PMessage(valueMap)
Expand Down Expand Up @@ -331,6 +332,7 @@ class Parser(
}

object JsonFormat {

import com.google.protobuf.wrappers
import scalapb_json.ScalapbJsonCommon._

Expand Down
13 changes: 0 additions & 13 deletions core/shared/src/test/scala/scalapb_circe/CodecSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,6 @@ class CodecSpec extends AnyFreeSpec with Matchers {
// Using asJson with an implicit printer includes the default value.
g.asJson mustBe Json.obj("numberOfStrings" -> Json.fromInt(0))
}

"decode using an implicit parser w/ non-standard settings" in {
implicit val parser: Parser = new Parser(preservingProtoFieldNames = true)

// Use the snake-case naming to define a Guitar Json object.
val j = Json.obj("number_of_strings" -> Json.fromInt(42))

// Using the regular JsonFormat parser decodes to the defaultInstance.
JsonFormat.fromJson[Guitar](j) mustBe Guitar.defaultInstance

// Using as[T] with an implicit parser decodes back to the original value (42).
j.as[Guitar] mustBe Right(Guitar(42))
}
}

"GeneratedEnum" - {
Expand Down
5 changes: 5 additions & 0 deletions core/shared/src/test/scala/scalapb_circe/JsonFormatSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,11 @@ class JsonFormatSpec extends AnyFlatSpec with Matchers with OptionValues {
new Parser().fromJsonString[MyTest]("""{"optEnum":2}""") must be(MyTest(optEnum = Some(MyEnum.V2)))
}

"TestProto" should "parse original field names" in {
new Parser().fromJsonString[MyTest]("""{"opt_enum":1}""") must be(MyTest(optEnum = Some(MyEnum.V1)))
new Parser().fromJsonString[MyTest]("""{"opt_enum":2}""") must be(MyTest(optEnum = Some(MyEnum.V2)))
}

"PreservedTestJson" should "be TestProto when parsed from json" in {
new Parser(preservingProtoFieldNames = true).fromJsonString[MyTest](PreservedTestJson) must be(TestProto)
}
Expand Down

0 comments on commit b955d37

Please sign in to comment.