使用 Scala Argonaut 解析 JSON 数组 [英] Parse JSON array using Scala Argonaut
问题描述
我正在使用 Scala &Argonaut,尝试解析以下 JSON:
<预><代码>[{"name": "苹果","type": "水果",尺寸":3},{"name": "果酱","类型": "调味品",大小":5},{"name": "牛肉","类型": "肉",尺寸":1}]并且正在努力解决如何迭代并将值提取到 List[MyType]
中,其中 MyType
将具有名称、类型和大小属性.
我很快会发布更具体的代码(我尝试了很多东西),但基本上我想了解游标的工作原理,以及如何遍历数组等.我尝试使用 \\
(downArray)移动到数组的头部,然后:->-
遍历数组,然后--\
(downField)不可用(至少 IntelliJ 不这么认为).所以问题是我该怎么做:
- 导航到数组
- 遍历数组(知道什么时候完成)
- 为每个字段提取字符串、整数等值 -
jdecode[String]
?as[String]
?
最简单的方法是为 MyType
定义一个编解码器.然后编译器会很高兴地为 List[MyType]
等构造一个解码器.我将在这里使用一个普通的类(不是案例类)来说明发生了什么:
class MyType(val name: String, val tpe: String, val size: Int)进口 argonaut._, Argonaut._隐式 def MyTypeCodec: CodecJson[MyType] = codec3((名称:字符串,tpe:字符串,大小:整数)=>新的 MyType(名称,tpe,大小),(myType: MyType) =>(myType.name, myType.tpe, myType.size))("名称"、"类型"、"大小")
codec3
需要两个参数列表.第一个有两个参数,它们允许您告诉如何从 Tuple3
创建 MyType
的实例,反之亦然.第二个参数列表让您指定字段的名称.
现在您可以编写如下内容(如果 json
是您的字符串):
Parse.decodeValidation[List[MyType]](json)
大功告成.
I'm using Scala & Argonaut, trying to parse the following JSON:
[
{
"name": "apple",
"type": "fruit",
"size": 3
},
{
"name": "jam",
"type": "condiment",
"size": 5
},
{
"name": "beef",
"type": "meat",
"size": 1
}
]
And struggling to work out how to iterate and extract the values into a List[MyType]
where MyType
will have name, type and size properties.
I will post more specific code soon (i have tried many things), but basically I'm looking to understand how the cursor works, and how to iterate through arrays etc. I have tried using \\
(downArray) to move to the head of the array, then :->-
to iterate through the array, then --\
(downField) is not available (at least IntelliJ doesn't think so).
So the question is how do i:
- navigate to the array
- iterate through the array (and know when I'm done)
- extract string, integer etc. values for each field -
jdecode[String]
?as[String]
?
The easiest way to do this is to define a codec for MyType
. The compiler will then happily construct a decoder for List[MyType]
, etc. I'll use a plain class here (not a case class) to make it clear what's happening:
class MyType(val name: String, val tpe: String, val size: Int)
import argonaut._, Argonaut._
implicit def MyTypeCodec: CodecJson[MyType] = codec3(
(name: String, tpe: String, size: Int) => new MyType(name, tpe, size),
(myType: MyType) => (myType.name, myType.tpe, myType.size)
)("name", "type", "size")
codec3
takes two parameter lists. The first has two parameters, which allow you to tell how to create an instance of MyType
from a Tuple3
and vice versa. The second parameter list lets you specify the names of the fields.
Now you can just write something like the following (if json
is your string):
Parse.decodeValidation[List[MyType]](json)
And you're done.
这篇关于使用 Scala Argonaut 解析 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!