2017-01-13 5 views
0

나는 최근 golang 및 easyjson과 함께 작업하기 시작했습니다. 이제 json 배열을 구조체로 비 정렬 화해야합니다. 그래서 여기 있어요.easyjson 배열을 구조체로 unmarshal 배열

는 들어오는 JSON 데이터는 모양이

[ 
    { 
     "Item1":true, 
     "Item2":"hello", 
     "Item3":{ 
      "A": 1, 
     }, 
    }, 
    ... 
] 

내 구조체 :

package something 

//easyjson:json 
type Item struct { 
    Item1 bool 
    Item2 string 
    Item3 SubItem 
} 

//easyjson:json 
type SubItem struct { 
    A int  
} 

이 (내가 * _easyjson.go 파일을 작성) 나는 easyjson 사용하는 것이 방법

그리고 여기이야 :

func ConvertJsonToItem(jsondata string) Item { 
    var item Item 
    lexer := jlexer.Lexer{Data: []byte(jsondata)} 

    item.UnmarshalEasyJSON(&lexer) 
    if lexer.Error() != nil { 
     panic(lexer.Error()) 
    } 
    return Item 
} 

json이 "Item"구조로 구성되어 있기 때문에 작동하지 않습니다. 그러나

var items []Item 

같은 것을 작성하는 것은 작동하지 않습니다 중 하나를 나는 조각에 UnmarshalEasyJSON을 실행할 수 없습니다 때문입니다. easyjson을 사용하고 있습니다. 왜냐하면 json 데이터를 처리하는 것이 fastet 방법이기 때문입니다.

내 질문은 : 어떻게 easyjson 개체 배열을 처리 할 수 ​​있습니다.

덧붙여서이 질문은 Unmarshal json into struct: cannot unmarshal array into Go value과 비슷하지만 사용자가 내장 json 패키지를 사용하고 easyjson을 사용하고 싶습니다. 미리 감사드립니다.

답변

0

무엇

//easyjson:json 
type ItemSlice []Item 

어떻습니까?

그런 다음

func ConvertJsonToItem(jsondata string) ItemSlice { 
    var items ItemSlice 
    lexer := jlexer.Lexer{Data: []byte(jsondata)} 

    items.UnmarshalEasyJSON(&lexer) 
    if lexer.Error() != nil { 
     panic(lexer.Error()) 
    } 
    return items 
} 

을 수행 할 수 있습니다 그리고 당신이 정말로 당신의 외부 코드에 ItemSlice을 원하지 않는 경우, 당신은 아직도 그것을 반환하기 전에 []Item로 다시 변환 할 수 있습니다 (하지만 당신은해야 할 것이다 나중에 마샬링하고 싶은 다른 방법으로는 똑같은 조작 ...).

관련 문제