0

我正在使用Kotlin并且Vert.x我有:

data class Product(
    var id: UUID? = UUID.randomUUID(),
    var name: String? = null,

    @JsonFormat(shape=JsonFormat.Shape.ARRAY)
    var pictures: JsonArray? = JsonArray()
)

我正在尝试Arraypictures. 我在请求正文中的 JSON 是这样的:

{
    "name": "Test",
    "pictures": [{"test": "a"}]
}

当我发送上面类似的Object内部消息时Array,我收到此错误:

[ERROR] 2020-01-02 13:04:26.519 [vert.x-eventloop-thread-0] Route - io.vertx.core.json.DecodeException: Failed to decode:Cannot deserialize instance of `java.util.ArrayList<java.lang.Object>` out of START_OBJECT token
 at [Source: (String)"{
        "name": "Test",
        "pictures": [{"test": "a"}]
}
"; line: 8, column: 15] (through reference chain: br.com.test.api.product.Product["pictures"]->io.vertx.core.json.JsonArray["list"])

但是如果我像这样发送一个空的Array,它的工作原理:

{
        "name": "Test",
        "pictures": []
}

我收到正确的回复:

{"id":"a6d2d319-42a9-4d4a-b16a-6bf4eb76e36d","name":"Test","pictures":[]}

所以问题是,我怎样才能在我的客户中发布Array一个Objects?谢谢!

4

1 回答 1

0

如果您能够拥有一个与“图片”数组中对象的形状相匹配的对象,那么以下应该可以工作:

import lombok.AllArgsConstructor
import lombok.Data
import lombok.NoArgsConstructor

@AllArgsConstructor
@NoArgsConstructor
@Data
class Product {

    var name: String? = null
    var pictures: List<Picture>? = null

    @Data
    class Picture {

        var test: String? = null

    }

}

示例使用为我工作:

@Test
fun deserializeProduct() {
    val mapper = ObjectMapper()
    val sample: String = "{" +
            "    \"name\": \"Test\"," +
            "    \"pictures\": [{\"test\": \"a\"}]" +
            "}"

    val json = mapper.readValue(sample, Product::class.java);
    assertEquals("a", json.pictures?.get(0)?.test)
}

如果图片数组中对象的内容每次都不是相同的形状,那么将图片列表设为 Map 可能是值得的:

var pictures: Map<String, *>?

然后您可以实现以下有效负载:

@Test
fun deserializeProduct() {
    val mapper = ObjectMapper()
    val sample: String = "{" +
            "    \"name\": \"Test\"," +
            "    \"pictures\": [{\"test\": \"a\"}, {\"differentKey\":\"b\",\"differentKey2\":1}]" +
            "}"

    val json = mapper.readValue(sample, Product::class.java);
    assertEquals("a", json.pictures?.get(0)?.get("test"))
    assertEquals("b", json.pictures?.get(1)?.get("differentKey"))
    assertEquals(1, json.pictures?.get(1)?.get("differentKey2"))
}
于 2020-01-03T09:16:33.420 回答