MagicArray use to data translate easily

lingdor
2 min readDec 26, 2023

--

In more cases, we need created more and more DTOs structs to deal with complex business,At time went by, the code will be maintained more and more differently.

If you are wroted with php language, You will maybe to thinking about, php array is flexible desgin.

But in go, you can use the MagicArray, you needn’t care type, you needn’t care about make more DTOs.

go get github.com/lingdor/magicarray@v0.0.6

CASE1 merge dto and output

package main

import (
"encoding/json"
"fmt"
"github.com/lingdor/magicarray/array"
"time"
)

type UserDTO struct {
Id int `json:"userid"`
Name string
}

type ScoreDTO struct {
Score int
ScoreTime time.Time
}

type AreaDto struct {
CityId int
City string
}

func dtosCommand() {

user := UserDTO{
Id: 1,
Name: "bobby",
}
score := ScoreDTO{
Score: 66,
ScoreTime: time.Now(),
}
area := AreaDto{
CityId: 10000,
City: "beij",
}

mix, _ := array.Merge(array.ValueofStruct(user), score, area)
mix = array.Pick(mix, "Id", "City", "Score")
if bs, err := json.Marshal(mix); err == nil {
fmt.Println(string(bs))
} else {
panic(err)
}

}

output

{"userid":1,"City":"newyork","Score":66}

CASE2 Column translate

package main

import (
"encoding/json"
"fmt"
"github.com/lingdor/magicarray/array"
)

type ColumnUserEntity struct {
Id int `json:"uid"`
UserName string
IsMale bool
}

func columnCommand() {

users := []ColumnUserEntity{
{
Id: 1,
UserName: "Bobby",
IsMale: true,
},
{
Id: 2,
UserName: "Lily",
IsMale: false,
},
}

usersArr := array.ValueOfSlice(users)
usersArr = array.WashColumn(usersArr, array.WashTagRuleJsonInitialLower())
if bs, err := json.Marshal(usersArr); err == nil {
fmt.Println(string(bs))
} else {
panic(err)
}

usersArr = array.Column(usersArr, "UserName")
if bs, err := json.Marshal(usersArr); err == nil {
fmt.Println(string(bs))
} else {
panic(err)
}

}

output

[{"uid":1,"userName":"Bobby","isMale":true},{"uid":2,"userName":"Lily","isMale":false}]
["Bobby","Lily"]Case3 Tag the fields
package main

import (
"encoding/json"
"fmt"
"github.com/lingdor/magicarray/array"
)

type UserEntity struct {
Id int `json:"uid"`
UserName string
IsMale bool
}

func tagCommand() {

users := UserEntity{
Id: 1,
UserName: "Bobby",
IsMale: true,
}

userArr := array.ValueofStruct(users)
userArr = array.SetTag(userArr, "Id", "json", "UserId")
if bs, err := json.Marshal(userArr); err == nil {
fmt.Println(string(bs))
} else {
panic(err)
}

}

output:

{"UserId":1,"UserName":"Bobby","IsMale":true}

--

--

lingdor
lingdor

No responses yet