[SCALA] 스칼라 2.10 + JSON 직렬화 및 역 직렬화
SCALA스칼라 2.10 + JSON 직렬화 및 역 직렬화
스칼라 2.10 Jerkson 및 리프트 JSON처럼 (당분간 적어도) 이전 라이브러리의 일부를 깨진 것 같습니다.
다음 목표 유용성이다 :
case class Person(name: String, height: String, attributes: Map[String, String], friends: List[String])
//to serialize
val person = Person("Name", ....)
val json = serialize(person)
//to deserialize
val sameperson = deserialize[Person](json)
하지만 문제가 발견 좋은 생성하는 방법을 기존의 스칼라 2.10와 그 일 JSON 직렬화를 해제하는 데 문제가 있습니다.
스칼라 2.10에서이 일을 가장 좋은 연습 방법이 있습니까?
해결법
-
==============================
1.잭슨은 빠른 JSON을 처리하는 자바 라이브러리입니다. Jerkson 프로젝트는 잭슨 랩,하지만 포기 것으로 보인다. 나는 기본 스칼라 데이터 구조 직렬화 및 역 직렬화 잭슨의 스칼라 모듈로 전환했습니다.
잭슨은 빠른 JSON을 처리하는 자바 라이브러리입니다. Jerkson 프로젝트는 잭슨 랩,하지만 포기 것으로 보인다. 나는 기본 스칼라 데이터 구조 직렬화 및 역 직렬화 잭슨의 스칼라 모듈로 전환했습니다.
그것을 얻으려면, 당신 build.sbt에 다음을 포함한다 :
libraryDependencies ++= Seq( "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.1.3", ... )
그런 다음 예는 (나는 잭슨 - 모듈 - 스칼라 테스트 파일에서 추출) 다음 잭슨 래퍼 그대로 작동합니다 :
import java.lang.reflect.{Type, ParameterizedType} import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.`type`.TypeReference; object JacksonWrapper { val mapper = new ObjectMapper() mapper.registerModule(DefaultScalaModule) def serialize(value: Any): String = { import java.io.StringWriter val writer = new StringWriter() mapper.writeValue(writer, value) writer.toString } def deserialize[T: Manifest](value: String) : T = mapper.readValue(value, typeReference[T]) private [this] def typeReference[T: Manifest] = new TypeReference[T] { override def getType = typeFromManifest(manifest[T]) } private [this] def typeFromManifest(m: Manifest[_]): Type = { if (m.typeArguments.isEmpty) { m.erasure } else new ParameterizedType { def getRawType = m.erasure def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray def getOwnerType = null } } }
그것의 간단한 성능의 비용 - 기타 스칼라 2.10 JSON 옵션은 프로그래밍 스칼라 책을 기반으로 트위터의 스칼라-JSON을 포함한다. 용도는 구문 분석 살짝 데친 스프레이 - JSON도있다. 마지막으로, 재생의 JSON은 외모의 좋은 처리하지만 재생 프로젝트에서 쉽게 분리되지 않습니다.
-
==============================
2.잭슨, 리프트 JSON 또는 장기 솔루션으로 자신의 기본 구현을 래핑 json4s을 언급 :
잭슨, 리프트 JSON 또는 장기 솔루션으로 자신의 기본 구현을 래핑 json4s을 언급 :
-
==============================
3.나는 진심으로 스칼라에서 JSON 지원을 위해 모험가 추천 할 수 있습니다. 당신이 당신의 고객 객체 직렬화를 구성 할 필요가있는 한 줄입니다 :
나는 진심으로 스칼라에서 JSON 지원을 위해 모험가 추천 할 수 있습니다. 당신이 당신의 고객 객체 직렬화를 구성 할 필요가있는 한 줄입니다 :
implicit lazy val CodecCustomer: CodecJson[Customer] = casecodec6(Customer.apply, Customer.unapply)("id","name","address","city","state","user_id")
즉 그것을 문자열로 그것을 밝혀 졌 .asJson 방법을 제공하는 클래스 포주 것입니다. 또한 그것을 구문 분석 문자열에 대한 방법 .decodeOption을 [목록 [고객] 줄 문자열 클래스를 포주 것입니다. 그것은 당신의 클래스 고급의 옵션을 처리합니다. 여기에 통과 테스트와 노동 계급은 당신이 모험가의 자식 클론에 드롭 할 수있는 실행의 주요 방법은 모든 일 잘 그것을보고 :
package argonaut.example import org.specs2.{ScalaCheck, Specification} import argonaut.CodecJson import argonaut.Argonaut._ case class Customer(id: Int, name: String, address: Option[String], city: Option[String], state: Option[String], user_id: Int) class CustomerExample extends Specification with ScalaCheck { import CustomerExample.CodecCustomer import CustomerExample.customers def is = "Stackoverflow question 12591457 example" ^ "round trip customers to and from json strings " ! { customers.asJson.as[List[Customer]].toOption must beSome(customers) } } object CustomerExample { implicit lazy val CodecCustomer: CodecJson[Customer] = casecodec6(Customer.apply, Customer.unapply)("id","name","address","city","state","user_id") val customers = List( Customer(1,"one",Some("one street"),Some("one city"),Some("one state"),1) , Customer(2,"two",None,Some("two city"),Some("two state"),2) , Customer(3,"three",Some("three address"),None,Some("three state"),3) , Customer(4,"four",Some("four address"),Some("four city"),None,4) ) def main(args: Array[String]): Unit = { println(s"Customers converted into json string:\n ${customers.asJson}") val jsonString = """[ | {"city":"one city","name":"one","state":"one state","user_id":1,"id":1,"address":"one street"} | ,{"city":"two city","name":"two","state":"two state","user_id":2,"id":2} | ,{"name":"three","state":"three state","user_id":3,"id":3,"address":"three address"} | ,{"city":"four city","name":"four","user_id":4,"id":4,"address":"four address"} |]""".stripMargin var parsed: Option[List[Customer]] = jsonString.decodeOption[List[Customer]] println(s"Json string turned back into customers:\n ${parsed.get}") } }
개발자들은 또한 도움이되고 사람들은 시작에 반응한다.
-
==============================
4.https://github.com/randhindi/jerkson에서 스칼라 2.10 지원 Jerkson의 포크 지금있다.
https://github.com/randhindi/jerkson에서 스칼라 2.10 지원 Jerkson의 포크 지금있다.
-
==============================
5.그래서, 오류 메시지의 부재와 잘못된 샘플 코드를 기반으로,이 더 바로 리프트 JSON 추출의 작동 방식을 이해하지 않는 문제입니다 의심하고있다. 제가 오해를 한 경우, 의견을 알려 주시기 바랍니다. 그래서, 내가 바로 여기에있어 경우에 당신이 필요합니다.
그래서, 오류 메시지의 부재와 잘못된 샘플 코드를 기반으로,이 더 바로 리프트 JSON 추출의 작동 방식을 이해하지 않는 문제입니다 의심하고있다. 제가 오해를 한 경우, 의견을 알려 주시기 바랍니다. 그래서, 내가 바로 여기에있어 경우에 당신이 필요합니다.
직렬화 :
import net.liftweb.json._ import Extraction._ implicit val formats = DefaultFormats case class Person(...) val person = Person(...) val personJson = decompose(person) // Results in a JValue
그런 다음 같은 것을 할 거라고 과정을 반전하기 :
// Person Json is a JValue here. personJson.extract[Person]
즉 당신이하는 데 문제가있는 부분이 아니라면, 그때 알려 주시기 않고 좀 더 도움이 될 내 대답을 수정하려고 할 수 있습니다.
from https://stackoverflow.com/questions/12591457/scala-2-10-json-serialization-and-deserialization by cc-by-sa and MIT license
'SCALA' 카테고리의 다른 글
[SCALA] 거기 비록 SBT는 지역 받는다는 저장소에서 파일을 찾을 수 없습니다 (0) | 2019.11.26 |
---|---|
[SCALA] 삼항 연산자 유사하려면? (0) | 2019.11.26 |
[SCALA] 스칼라 : 목록 대 무기 호 () (0) | 2019.11.25 |
[SCALA] 스칼라에서 영구 데이터 구조 (0) | 2019.11.25 |
[SCALA] 세트, 펑 및 식의 혼란 (0) | 2019.11.25 |