04-20.eri-test Azure Functions技巧:了解GSON JsonSyntaxException

I was working on Azure Functions using Azure Event Hubs trigger and this error popped up:

Result: Failure
Exception: IllegalStateException: 预期为BEGIN_OBJECT,但为BEGIN_ARRAY at line 1 column 2 path $
Stack: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at com.google.gson.Gson.fromJson(Gson.java:841)

.... //omitted for brevity

What could possibly go wrong?

TL;DR Please don't forget to use the right 基数 with when using Event Hubs Trigger with Azure Functions, and if you do, hopefully you stumble across this blog post if you Google it on Bing! ;-)

the (slightly) longer version...

这个错误对我来说是新的。 经过进一步的自省,我意识到问题与Azure Functions平台无法调用函数方法本身有关(即它与函数逻辑本身无关)

By the way, there are many features to make troubleshooting Azure Functions easier

Azure Functions uses the gson library to serialize/de-serialze payloads

这是该方法的一个片段:

@FunctionName("process数据")
public void process(
    @EventHubTrigger(name = "event", eventHubName = "", connection = "EventHubConnectionString") 
    数据 data, final ExecutionContext context) {
        //implementation
    }

在这种情况下,它无法将事件中心负载转换为Data该方法预期的POJO。

I looked into the Azure Functions Java API docs to confirm whether I was using the @EventHubTrigger properly. And I stumbled across the cardinality property

这是定义:

触发输入的基数。 如果输入是单个消息,则选择“一个”;如果输入是消息的数组,则选择“许多”。 如果未指定,则默认为“很多”..,其默认值为基数

啊哈! 现在,理解错误消息并不难Expected BEGIN_OBJECT but was BEGIN_ARRAY-因为基数,该平台正尝试序列化以下内容的列表/数组DataPOJO,但是该方法只期望一个。 包括cardinality明确地(基数一)是解决方案,即

@EventHubTrigger(
    name = "event", 
    eventHubName = "", 
    connection = "EventHubConnectionString",
    cardinality = Cardinality.ONE) 

另一种方法是更改​​签名以接受List<Data>并选择列表中的第一项,例如data.get(0)

目前为止就这样了。 如果您发现这有帮助,请显示一些❤️并继续关注更多🙌!

from: https://dev.to//azure/azure-functions-tip-making-sense-of-gson-jsonsyntaxexception-5355

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值