문제:
다음과 같은 필드가 있는 구조체로 JSON을 역마샬링합니다. 문자열 조각인 반면, JSON 값은 구분 기호를 사용하여 분할해야 하는 단일 문자열입니다.
<code class="json">{ "student_number": 1234567, "name": "John Doe", "subjects": "Chemistry-Maths-History-Geography" }</code>
<code class="go">type Student struct { StudentNumber int Name string Subjects []string }</code>
답변:
사용자 정의 문자열 슬라이스 유형을 지정하고 json.Unmarshaler를 구현하여 분할을 처리합니다.
<code class="go">type strslice []string func (ss *strslice) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return err } *ss = strings.Split(s, "-") return nil }</code>
구조체에서 이 사용자 정의 유형을 사용합니다.
<code class="go">type Student struct { StudentNumber int Name string Subjects strslice }</code>
코드 예:
<code class="go">func main() { var s Student err := json.Unmarshal([]byte(src), &s) fmt.Println(s, err) } const src = `{"student_number":1234567, "name":"John Doe", "subjects":"Chemistry-Maths-History-Geography"}`</code>
출력:
{1234567 John Doe [Chemistry Maths History Geography]} <nil>
위 내용은 Golang에서 구분 기호를 사용하여 JSON 문자열을 슬라이스로 역마샬링하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!