2017-09-07 1 views
1

다음과 같은 오류가 있습니다 (0은 3이 아님). 이유를 모르겠습니다. 이견있는 사람?JSON의 Circe 추출 목록

class Temp extends MyCirceExtendingClass { 
    def temp(json: Json) = { 
    root.otherNames.each.otherName.string.getAll(json) 
    } 
} 

val json = Json.fromString(
    s""" 
    |{ 
    | id: 1, 
    | name: "Robert", 
    | isEmployee: false, 
    | otherNames: [ 
    |  { 
    |   id: 1, 
    |   otherName: "Rob" 
    |  }, 
    |  { 
    |   id: 2, 
    |   otherName: "Bob" 
    |  }, 
    |  { 
    |   id: 3, 
    |   otherName: "Robby" 
    |  } 
    | 
    | ] 
    |} 
    """.stripMargin) 

val response = new Temp().temp(json) 
response.size shouldEqual 3 

답변

1

먼저 Json.fromString은 인수를 구문 분석하지 않고 Json으로 래핑합니다. 둘째, Json 문자열의 형식이 잘못되었습니다. 필드 이름은 따옴표로 묶어야합니다. 이 문제를 해결하면 렌즈가 정확한 결과를 제공합니다.

import cats.implicits._ 
import io.circe.optics.JsonPath.root 
import io.circe.parser.parse 
import io.circe.Json 

val json = parse(
    s""" 
    |{ 
    | "id": 1, 
    | "name": "Robert", 
    | "isEmployee": false, 
    | "otherNames": [ 
    |  { 
    |   "id": 1, 
    |   "otherName": "Rob" 
    |  }, 
    |  { 
    |   "id": 2, 
    |   "otherName": "Bob" 
    |  }, 
    |  { 
    |   "id": 3, 
    |   "otherName": "Robby" 
    |  } 
    | 
    | ] 
    |} 
""".stripMargin).getOrElse(Json.Null) 

root.otherNames.each.otherName.string.getAll(json) 

res1: List[String] = List(Rob, Bob, Robby)