valyala / fastjson

Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Query: Is there any method with which I can convert Value to my defined struct.

princekhanna13 opened this issue · comments

HI,

fastjson seems very good library which I would love to have in my project. In one of my use cases, I want to convert a value struct to my defined struct. Is there any method available in fastjson for that?

Just write the corresponding function that unmarshals JSON to custom struct and use the function. For instance:

type myStruct struct {
    Foo []byte
    A []int
}

var myStructParsers fastjson.ParserPool

// Unmarshal unmarshals JSON s to ms.
func (ms *myStruct) Unmarshal(s string) {
    p := myStructParsers.Get()
    defer myStructParsers.Put(p)
    v, err := p.Parse(`{"foo": "bar", "a": [1,2,3]}`)
    if err != nil {
        return err
    }
    ms.Foo = append(ms.Foo[:0], v.GetStringBytes("foo")...)
    ms.A = ms.A[:0]
    for _, av := range v.GetArray("a") {
        ms.A = append(ms.A, av.GetInt()
    }
    return nil
}

Thanks man for the suggestion.

type System struct {
	SystemNumber    string  ` json:"system_number"`
	SystemID        string  `json:"system_id"`
	ExternalID      string  `json:"external_id"`
	SystemRole      string  `json:"system_role"`
	LifecycleStatus string  `json:"lifecycle_status"`
	BusinessType    string  `json:"business_type"`
	Location        *string `json:"location"`
}

systems := value.GetArray("systems")
system := test.System{}
json.Unmarshal([]byte(systems[0].String()), &system)

Payload is

{
	"replication_mode": "FULL",
	"version": "V1.0",
	"notification_id": "1",
	"systems": [
		{
			"change_mode": "U",
			"system_number": "1",
			"system_id": "1",
			"external_id": "1",
			"system_role": "1",
			"lifecycle_status": "L",
			"location": "1",
			"business_type": "1"
		}
	]
}

I am looking for some generic unmarshal which can convert json string to my struct. Ablove given unmarshal is from "encoding/json". Is there similar unmarshal present in fastjson?

@princekhanna13 , fastjson doesn't provide generic unmarshaling to user-defined struct. There are no plans for adding such a functionality, since it will be slow. It should rely on Go reflection, which allocates a lot, losing performance advantage of fastjson over encoding/json.

Ok, I understand. I will make custom unmarshal for my structs.

Closing the issue.

Thanks.