标签: marshalling

将 float[][] 编组为 float**

假设我有一个带有原型的 C++ 函数

int someFunction(const float ** raws)
Run Code Online (Sandbox Code Playgroud)

如何使用float[][]C# 中的参数调用此函数?可能不使用不安全代码。

c# c++ pinvoke marshalling

1
推荐指数
1
解决办法
298
查看次数

如何覆盖 Go 结构中的 json 标签?

我想编组该结构的一部分:

type ValueSet struct {
    Id           string                       `json:"id" bson:"_id"`
    Url          string                       `bson:"url,omitempty" json:"url,omitempty"`
    Identifier   *Identifier                  `bson:"identifier,omitempty" json:"identifier,omitempty"`
    Version      string                       `bson:"version,omitempty" json:"version,omitempty"`
    Name         string                       `bson:"name,omitempty" json:"name,omitempty"`
    Status       string                       `bson:"status,omitempty" json:"status,omitempty"`
    Experimental *bool                        `bson:"experimental,omitempty" json:"experimental,omitempty"`
    Publisher    string                       `bson:"publisher,omitempty" json:"publisher,omitempty"`
    Contact      []ValueSetContactComponent   `bson:"contact,omitempty" json:"contact,omitempty"`
    Date         *FHIRDateTime                `bson:"date,omitempty" json:"date,omitempty"`
    LockedDate   *FHIRDateTime                `bson:"lockedDate,omitempty" json:"lockedDate,omitempty"`
    Description  string                       `bson:"description,omitempty" json:"description,omitempty"`
    UseContext   []CodeableConcept            `bson:"useContext,omitempty" json:"useContext,omitempty"`
    Immutable    *bool                        `bson:"immutable,omitempty" json:"immutable,omitempty"`
    Requirements string                       `bson:"requirements,omitempty" json:"requirements,omitempty"`
    Copyright    string                       `bson:"copyright,omitempty" json:"copyright,omitempty"`
    Extensible   *bool                        `bson:"extensible,omitempty" json:"extensible,omitempty"`
    CodeSystem   *ValueSetCodeSystemComponent `bson:"codeSystem,omitempty" json:"codeSystem,omitempty"`
    Compose …
Run Code Online (Sandbox Code Playgroud)

json marshalling go hl7-fhir

1
推荐指数
1
解决办法
2107
查看次数

如何说服 UnmarshalJSON 使用切片子类型?

我想要使​​用base64 RawURLEncoding而不是.json 来编组和解组 JSON 的字节切片StdEncoding。没有明显的方法可以通过编码/json包来做到这一点,这是明智的,所以我想我应该创建一个子类型来做到这一点。

type Thing []byte
Run Code Online (Sandbox Code Playgroud)

编组支持很简单:

func (thing Thing) MarshalJSON() ([]byte, error) {
    if thing == nil {
        return []byte("null"), nil
    }
    return []byte(`"` + base64.RawURLEncoding.EncodeToString(thing) + `"`), nil
}
Run Code Online (Sandbox Code Playgroud)

但 Unmarshal 却没有那么多。我追踪了编码/json源,并提出了:

func (thing Thing) UnmarshalJSON(data []byte) error {
    v := reflect.ValueOf(&thing)
    if len(data) == 0 || data[0] == 'n' { // null
        v.SetBytes([]byte{})
        return nil
    }
    data = data[1 : len(data)-1]
    dst := make([]byte, base64.RawURLEncoding.DecodedLen(len(data)))
    n, err := …
Run Code Online (Sandbox Code Playgroud)

reflection json marshalling go slice

1
推荐指数
1
解决办法
872
查看次数

带有嵌入式结构的golang json编组不起作用

我正在尝试扩展 AWS S3 Bucket 类型以包含附加格式并将其编组为 JSON,但编组不会选择附加字段

这就是我所拥有的

// AWS has this struct already
type Bucket struct {
    // Date the bucket was created.
    CreationDate *time.Time `type:"timestamp" 
    timestampFormat:"iso8601"`

    // The name of the bucket.
    Name *string `type:"string"`
    // contains filtered or unexported fields
}

// Extended struct
type AWSS3Bucket struct {
    s3.Bucket
    location     string
}

somefunc()
{
    var region string = "us-west-1"
    aws_s3_bucket := AWSS3Bucket{Bucket:*bucket, location:region}
    jsonString, err := json.Marshal(&aws_s3_bucket)
    fmt.Printf("%s\n", jsonString)
}
Run Code Online (Sandbox Code Playgroud)

我得到的只是 Bucket 的编码。例如,我上面的输出总是这样,不包括区域

{"CreationDate":"2016-10-17T22:33:14Z","Name":"test-bucket"}
Run Code Online (Sandbox Code Playgroud)

知道为什么该区域没有被编组到 json 缓冲区中吗?

json marshalling go

1
推荐指数
1
解决办法
2053
查看次数

将 map[string]string 嵌入 Go JSON 编组中,无需额外的 JSON 属性(内联)

有没有办法嵌入map[string]string内联?

我得到的是:

{
    "title": "hello world",
    "body": "this is a hello world post",
    "tags": {
        "hello": "world"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的意思是嵌入或内联是预期的结果,如下所示:

    {
    "title": "hello world",
    "body": "this is a hello world post",
    "hello": "world"
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码...我从 yaml 文件加载信息,并希望从上面返回所需格式的 JSON:

这是我的 yaml:

title: hello world
body: this is a hello world post
tags:
  hello: world
Run Code Online (Sandbox Code Playgroud)

这是我的 Go 代码:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"

    "gopkg.in/yaml.v2"
)

type Post struct {
    Title string            `yaml:"title" json:"title"`
    Body  string            `yaml:"body" json:"body"`
    Tags …
Run Code Online (Sandbox Code Playgroud)

json marshalling go

1
推荐指数
1
解决办法
3330
查看次数

来自特定索引的字节数组作为 C# 中的结构,而不进行复制

目前,我编写了客户端-服务器垃圾代码,并处理了大量通过网络传递的 C++ 结构。我知道这里提供的方法从字节数组中读取 C# 中的 C/C++ 数据结构,但它们都是关于制作副本的。

我想要这样的东西:

struct/*or class*/ SomeStruct
{
    public uint F1;
    public uint F2;
    public uint F3;
}
Run Code Online (Sandbox Code Playgroud)

稍后在我的代码中我想要类似的东西:

byte[] Data; //16 bytes that I got from network
SomeStruct PartOfDataAsSomeStruct { get { return /*make SomeStruct instance based on this.Data starting from index 4, without copying it. So when I do PartOfDataAsSomeStruct.F1 = 132465; it also changes bytes 4, 5, 6 and 7 in this.Data.*/; } }
Run Code Online (Sandbox Code Playgroud)

如果可以的话,请问如何实现?

c# arrays struct marshalling

1
推荐指数
1
解决办法
498
查看次数

解组字符串 json 时在输入字节 0 处使用非法的 base64 数据

我将我的数据存储在一个 redis 数据库中,当我要求它时,我得到了一个有效的 json。json 看起来像这样:

{"Data":"hi","Hash":"000f7dcfca98450a0f405384db3878c1956cb98309e63cf2d0a963cff9f17260","PrevHash":"000daf177434acd55a3284787b793a3453c3d70eacdb9a84f5faed43adb2ff58","Nonce":8504,"TimeStamp":1611498968}
Run Code Online (Sandbox Code Playgroud)

这是一个有效的 json 字符串(Go 省略前导和尾引号),但在解组时出现此错误。 illegal base64 data at input byte 0

err = json.Unmarshal([]byte(item), &block)

type Block struct {
    Data      []byte
    Hash      []byte
    PrevHash  []byte
    Nonce     int
    TimeStamp int64
}

func (chain *BlockChain) AddBlock(data string) {
    var lastHash []byte

    item, err := chain.Database.Get(ctx, "lastHash").Result()
    Handle(err)
    lastHash = []byte(item)
    newBlock := createBlock(data, lastHash)

    _, err = chain.Database.Set(ctx, StrHash(newBlock.Hash), newBlock, 0).Result()
    Handle(err)
    _, err = chain.Database.Set(ctx, "lastHash", newBlock.Hash, 0).Result()
}

func (chain *BlockChain) Iterator() *BlockChainIterator { …
Run Code Online (Sandbox Code Playgroud)

json marshalling go

1
推荐指数
1
解决办法
728
查看次数

Go 中类型名称处理与encoding/json 的等价性是什么?

散文简短描述

\n

我有一种情况,我想将 JSON 数据解组到一个结构数组(一个FooBar多个),所有结构都实现一个通用接口MyInterface。此外,实现该接口的所有合格结构类型都有一个公共字段,我Discrimininator在下面的示例中命名了该字段。\nDiscriminator\xc2\xb9 允许为每个 Discriminator 值唯一地找到正确的结构类型。

\n

问题和错误消息

\n

但在解组过程中,代码并不“知道”哪个是正确的“目标”类型。解组失败。

\n
\n

无法将对象解组为 main.MyInterface 类型的 Go 值

\n
\n

MWE 在

\n

https://play.golang.org/p/Dw1hSgUezLH

\n
package main\n\nimport (\n    "encoding/json"\n    "fmt"\n)\n\ntype MyInterface interface {\n    // some other business logic methods go here!\n    GetDiscriminator() string // GetDiscriminator returns something like a key that is unique per struct type implementing the interface\n}\n\ntype BaseStruct struct {\n    Discriminator string // will always be "Foo" for all …
Run Code Online (Sandbox Code Playgroud)

polymorphism marshalling go

1
推荐指数
1
解决办法
590
查看次数

当 []byte 工作正常时无法封送 json.RawMessage

可以在此处找到可重现的示例https://go.dev/play/p/wNyhezDfxVt

我想用字段封送 ( json.Marshal(...)) 一个结构体json.RawMessage

type Container1 struct {
    OldValue json.RawMessage `json:"old"`
    NewValue json.RawMessage `json:"new"`
}
Run Code Online (Sandbox Code Playgroud)

但是,它抱怨以下错误:

error calling MarshalJSON for type json.RawMessage: invalid character 'h' looking for beginning of value
Run Code Online (Sandbox Code Playgroud)

进行更改json.RawMessage[]byte解决问题,但请注意,这json.RawMessage只不过是[]byte

error calling MarshalJSON for type json.RawMessage: invalid character 'h' looking for beginning of value
Run Code Online (Sandbox Code Playgroud)

我想仍然能够使用json.RawMessage,有什么帮助吗?谢谢!

json marshalling go

1
推荐指数
1
解决办法
1629
查看次数

Golang Marshal/Unmarshal JSON包含导出和未导出的字段

我已经看到很多方法来编组/解组只有未导出字段的结构.但是我怎么能用混合领域呢?

给定一个结构:

type Test struct {
    fieldA string `json:"fieldA"`
    FieldB int    `json:"fieldB"`
    FieldC string `json:"fieldC"`
}
Run Code Online (Sandbox Code Playgroud)

如何编写MarshalJSON/UnmarshalJSON函数,以便fieldA与FieldB和FieldC一起传输?

以下编译,但在运行时溢出调用堆栈.我的猜测是我递归编组对象,但我不确定在编码时如何保留导出和未导出的字段.

func (t *Test) MarshalJSON() ([]byte, error) {
    return json.Marshal(struct {
         *Test
         FieldA string `json:"fieldA"`
    }{
         t,
         t.fieldA,
    })
}

func (t *Test) UnmarshalJSON(b []byte) error {
    return json.Unmarshal(b, &t)
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?或者我应该重新考虑我的数据结构,也许只是导出该字段?

注意:我知道我可以手动执行每个字段,但是如果可能的话,我希望避免更新代码更易于管理.

json marshalling go unmarshalling

0
推荐指数
2
解决办法
4878
查看次数

标签 统计

marshalling ×10

go ×8

json ×7

c# ×2

arrays ×1

c++ ×1

hl7-fhir ×1

pinvoke ×1

polymorphism ×1

reflection ×1

slice ×1

struct ×1

unmarshalling ×1