Programing

Go에서 부분적으로 JSON을 맵으로 비 정렬 화

crosscheck 2020. 9. 14. 07:58
반응형

Go에서 부분적으로 JSON을 맵으로 비 정렬 화


내 웹 소켓 서버는 JSON 데이터를 수신하고 마샬링 해제합니다. 이 데이터는 항상 키 / 값 쌍이있는 개체에 래핑됩니다. 키 문자열은 값 식별자 역할을하여 Go 서버에 어떤 종류의 값인지 알려줍니다. 어떤 유형의 값을 알면 올바른 유형의 구조체로 값을 비 정렬 화하는 JSON으로 진행할 수 있습니다.

각 json- 객체에는 여러 키 / 값 쌍이 포함될 수 있습니다.

예제 JSON :

{
    "sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
    "say":"Hello"
}

"encoding/json"작업을 수행하기 위해 패키지를 사용하는 쉬운 방법 이 있습니까?

package main

import (
    "encoding/json"
    "fmt"
)

// the struct for the value of a "sendMsg"-command
type sendMsg struct {
    user string
    msg  string
}
// The type for the value of a "say"-command
type say string

func main(){
    data := []byte(`{"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},"say":"Hello"}`)

    // This won't work because json.MapObject([]byte) doesn't exist
    objmap, err := json.MapObject(data)

    // This is what I wish the objmap to contain
    //var objmap = map[string][]byte {
    //  "sendMsg": []byte(`{"user":"ANisus","msg":"Trying to send a message"}`),
    //  "say": []byte(`"hello"`),
    //}
    fmt.Printf("%v", objmap)
}

어떤 종류의 제안 / 도움을 주셔서 감사합니다!


이는 map[string]*json.RawMessage.

var objmap map[string]*json.RawMessage
err := json.Unmarshal(data, &objmap)

추가 구문 분석 sendMsg을 위해 다음과 같이 할 수 있습니다.

var s sendMsg
err = json.Unmarshal(*objmap["sendMsg"], &s)

의 경우 say동일한 작업을 수행하고 문자열로 역 정렬화할 수 있습니다.

var str string
err = json.Unmarshal(*objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/RJbPSgBY6gZ


Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

Example:

func main() {
    jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`

    car := NewCar()

    i := iojson.NewIOJSON()

    if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    }

    // populating data to a live car object.
    if v, err := i.GetObjFromArr(0, car); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    } else {
        fmt.Printf("car (original): %s\n", car.GetName())
        fmt.Printf("car (returned): %s\n", v.(*Car).GetName())

        for k, item := range car.ItemArr {
            fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
        }

        for k, item := range v.(*Car).ItemArr {
            fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
        }
    }
}

Sample output:

car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen

참고URL : https://stackoverflow.com/questions/11066946/partly-json-unmarshal-into-a-map-in-go

반응형