Спрей десериализации проблема - PullRequest
0 голосов
/ 17 октября 2018

У меня есть json

{"status":"ok","totalResults":9,"articles":[{"source":{"id":"abc-news","name":"ABC News"},"author":"David Rind and Kelly Terez","title":"'Start Here': Midterms, marijuana in Canada. What you need to know to start your day.","description":"It's Wednesday, Oct. 17, 2018. Here's what you need to start your day.","url":"https://abcnews.go.com/US/start-here-trumps-saudi-ties-us-ambassador-israel-visits/story?id=58536629","urlToImage":"https://s.abcnews.com/images/US/pompeo-sh-er-181016_hpMain_16x9_992.jpg","publishedAt":"2018-10-17T00:00:00Z","content":"It's Wednesday, Oct. 17, 2018. Here's what you need to start your day: 1. Trump likens Khashoggi disappearance to Kavanaugh As U.S. lawmakers and critics question the Saudi government's pledge for an \"independent investigation\" into the disappearance of Washi… [+7002 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"John Verhovek","title":"O'Rourke attacks Cruz as 'dishonest' in testy 2nd Texas Senate debate","description":"GOP Sen. Ted Cruz and Democratic Rep. Beto O'Rourke traded a number of sharp barbs in the second Texas Senate debate as the closely-watched comes to a close.","url":"https://abcnews.go.com/Politics/orourke-attacks-cruz-dishonest-testy-texas-senate-debate/story?id=58544213","urlToImage":"https://s.abcnews.com/images/Politics/texas-debate-ap-mo-20181017_hpMain_16x9_992.jpg","publishedAt":"2018-10-17T00:00:00Z","content":"Interested in Midterm Elections? Add Midterm Elections as an interest to stay up to date on the latest Midterm Elections news, video, and analysis from ABC News. With just three weeks until voters decide a surprisingly pivotal U.S. Senate race in the state of… [+5834 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"The Associated Press","title":"Tesla secures land for Shanghai factory, first outside US","description":"The electric car maker signed a deal on a 210-acre site outside Shanghai, China.","url":"https://abcnews.go.com/Business/wireStory/tesla-secures-land-shanghai-factory-us-58553017","urlToImage":"https://s.abcnews.com/images/Business/WireAP_e3dccffea16a4b46b1be59200a6e3991_16x9_992.jpg","publishedAt":"2018-10-17T00:00:00Z","content":"Interested in Tesla? Add Tesla as an interest to stay up to date on the latest Tesla news, video, and analysis from ABC News. Electric auto brand Tesla Inc. said it signed an agreement Wednesday to secure land in Shanghai for its first factory outside the Uni… [+3204 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"The Associated Press","title":"Pakistan executes man convicted of killing 8 children","description":"The country's top court rejected a request for his public hanging.","url":"https://abcnews.go.com/International/wireStory/serial-killer-children-executed-pakistani-prison-58548375","urlToImage":"https://s.abcnews.com/images/International/WireAP_4aaa3f34a9204070b34031eacfe247b4_16x9_992.jpg","publishedAt":"2018-10-17T00:00:00Z","content":"A man convicted of killing eight children was executed at a Pakistani prison early Wednesday after the country's top court rejected a request for his public hanging, officials said. Mohammad Imran was hanged in the eastern city of Lahore in the presence of th… [+1583 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"The Associated Press","title":"Newly published files confirm plan to move Assange to Russia","description":"Ecuadorean documents have laid bare an unorthodox attempt to extricate Assange.","url":"https://abcnews.go.com/International/wireStory/newly-published-files-confirm-plan-move-assange-russia-58552865","urlToImage":null,"publishedAt":"2018-10-17T00:00:00Z","content":"Interested in WikiLeaks? Add WikiLeaks as an interest to stay up to date on the latest WikiLeaks news, video, and analysis from ABC News. Ecuadorean government documents have laid bare an unorthodox attempt to extricate Assange from his embassy hideaway in Lo… [+729 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"The Associated Press","title":"Reports: 10 feared dead in gas explosion at Crimean college","description":"Russian news agencies say at least 40 people have been wounded in the incident.","url":"https://abcnews.go.com/International/wireStory/reports-10-feared-dead-gas-explosion-crimean-college-58553239","urlToImage":null,"publishedAt":"2018-10-17T00:00:00Z","content":"Interested in Russia? Add Russia as an interest to stay up to date on the latest Russia news, video, and analysis from ABC News. Russian news agencies say that up to 10 people may have been killed and at least 40 others wounded by a natural gas explosion at a… [+482 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"Conor Finnegan","title":"Trump: Saudi crown prince 'totally denied any knowledge' of Jamal Khashoggi's fate","description":"The Saudis are weighing accepting culpability for Khashoggi's death. It's unclear what explanation they would give, a source with knowledge of their plans told ABC News.","url":"https://abcnews.go.com/Politics/amid-questions-jamal-khashoggis-death-saudis-weighing-accepting/story?id=58530162","urlToImage":"https://s.abcnews.com/images/International/pompeo-saudi-arabia-01-mohammed-bin-salman-ap-jc-181016_hpMain_16x9_992.jpg","publishedAt":"2018-10-16T00:00:00Z","content":"Saudi Arabia's young crown prince is again denying any involvement in the disappearance of Washington Post columnist Jamal Khashoggi, according to President Donald Trump, who tweeted that he spoke with him and Secretary of State Mike Pompeo Tuesday after disp… [+5510 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"Emily Shapiro","title":"Hurricane Michael death toll climbs to 26","description":"Sixteen people died in Florida and 12 of those deaths were in Bay County.","url":"https://abcnews.go.com/US/hurricane-michael-death-toll-climbs-26-including-16/story?id=58539971","urlToImage":"https://s.abcnews.com/images/US/hurricane-6-gty-er-181015_hpMain_16x9_992.jpg","publishedAt":"2018-10-16T00:00:00Z","content":"Hurricane Michael's death toll has climbed to 26, The Associated Press said Tuesday. Sixteen people died in Florida, state officials said, according to the AP, and 12 of those deaths were in Bay County, which was hit hard by the monster Category 4 storm. SLID… [+1152 chars]"},{"source":{"id":"abc-news","name":"ABC News"},"author":"ABCNews","title":"Trump calls Stormy Daniels 'horseface' in his reaction to dismissal of her suit","description":"He hurled the insult in his first public response to her suit's dismissal.","url":"https://abcnews.go.com/Politics/president-trump-calls-stormy-daniels-horseface-reaction-dismissal/story?id=58532716","urlToImage":"https://s.abcnews.com/images/International/stormy-daniels-ap-mem-181016_hpMain_16x9_992.jpg","publishedAt":"2018-10-16T00:00:00Z","content":"President Trump in a tweet called Stormy Daniels, the porn star who alleges she had an affair with him, \"horseface.\" Interested in Donald Trump? Add Donald Trump as an interest to stay up to date on the latest Donald Trump news, video, and analysis from ABC N… [+753 chars]"}]}

, который я преобразую в объект scala с помощью spray-json.Мои классы дел выглядят следующим образом:

  case class SourceId(id: String, name: String)

  case class Articles(source: SourceId, author: String, title: String, description: String, url: String, urlToImage: String, publishedAt: String, content: String)

  case class GetNewsFromSingleSourceResponse(status: String, totalResults: Long, articles: Seq[Articles])

Я создал черту, которая расширяет DefaultJsonProtocol и SprayJsonSupport, где я объявляю последствия для преобразования json.

trait JsonSupporter extends DefaultJsonProtocol with SprayJsonSupport {

  implicit val SourceIdFormat = jsonFormat2(SourceId)
  implicit val ArticlesFormat = jsonFormat8(Articles)
  implicit val GetNewsFromSingleSourceResponseFormat = jsonFormat3(GetNewsFromSingleSourceResponse)
}

Теперь, когда я десериализую этоJSON с помощью спрея

news.parseJson.convertTo[GetNewsFromSingleSourceResponse]

Я получаю сообщение об ошибке как

spray.json.DeserializationException: Expected String as JsString, but got null

Кто-нибудь может указать, где я ошибаюсь в моем подходе?

1 Ответ

0 голосов
/ 17 октября 2018

Прежде всего вам нужно сделать поле urlToImage из Articles равным Option[String].Тогда вам нужно использовать черту NullOptions, как это

trait JsonSupporter extends DefaultJsonProtocol with SprayJsonSupport with NullOptions {

  implicit val SourceIdFormat = jsonFormat2(SourceId)
  implicit val ArticlesFormat = jsonFormat8(Articles)
  implicit val GetNewsFromSingleSourceResponseFormat = jsonFormat3(GetNewsFromSingleSourceResponse)
}
...