如何使用结构链代码返回“不允许附加属性记录”

问题描述

使用“ github.com/hyperledger/fabric-contract-api-go/contractapi”编写链式代码时出现错误

@H_404_2@type PaginatedQueryResult struct { Records []asset `json:"records"` FetchedRecordsCount int32 `json:"fetchedRecordsCount"` Bookmark string `json:"bookmark"` Completed bool `json:"completed"` }

当记录为零时,报告错误:“ asset_transfer_ledger链码值与架构不匹配:\ n 1. return.records:无效的类型。期望:数组,给定:null”,然后更新 这样的PaginatedQueryResult结构:

@H_404_2@type PaginatedQueryResult struct { Records []asset `json:"records,omitempty" Metadata:",optional" ` FetchedRecordsCount int32 `json:"fetchedRecordsCount"` Bookmark string `json:"bookmark"` Completed bool `json:"completed"` }

如果Records为nil,可以,但是如果Records为nil,则出现错误:“不允许其他属性记录”

解决方法

感谢您发布此帖子,您使我发现了代码中的错误。问题是代码假定json标记仅是名称,并且不希望,omitempty,因此元数据模式最终具有属性records,omitempty,因此,在提供记录值时找不到在架构中作为有效属性。由于元数据标记会覆盖任何json值,因此在确定核心代码之前的解决方案是将名称添加到元数据标记以及JSON中,因此您的结构将变为:

type PaginatedQueryResult struct {
   Records             []asset `json:"records,omitempty" metadata:"records,optional" `  
   FetchedRecordsCount int32  `json:"fetchedRecordsCount"`   
   Bookmark            string `json:"bookmark"`   
   Completed           bool   `json:"completed"`
}

请注意,出于编组目的,记录位于JSON标签中,而元数据标签则位于记录中。

我在这里为此问题打开了一个JIRA:https://jira.hyperledger.org/browse/FABCAG-31