graphql-go / graphql

An implementation of GraphQL for Go / Golang
MIT License
9.92k stars 840 forks source link

Help: Unable to Unmarshal from JSON to Struct #299

Open JulienBreux opened 6 years ago

JulienBreux commented 6 years ago

I have this JSON:

{
    "myField": {
        "name": "",
        "type": {
            "name": "String",
            "description": "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text."
        },
        "args": {
            "myFieldName": {
                "type": {
                    "ofType": {
                        "name": "String",
                        "description": "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text."
                    }
                },
                "defaultValue": null,
                "description": ""
            },
        },
        "deprecationReason": "",
        "description": "Test"
    }
}

When I want to unmarshal:

var fields graphql.Fields
var fieldsEncoded []byte

// fieldsEncoded = ...

if err := json.Unmarshal(fieldsEncoded, &fields); err != nil {
    fmt.Println(err)
}

I have this result:

json: cannot unmarshal object into Go struct field Field.type of type graphql.Output

Do you have an idea @chris-ramon or @dvic?

JulienBreux commented 6 years ago

I try to unmarshal like this: (in definition.go)

type Field struct {
    // ...
}

func (f Field) UnmarshalJSON(b []byte) error {
    var tmp map[string]interface{}

    if err := json.Unmarshal(b, &tmp); err != nil {
        return err
    }

    for k, v := range tmp {
        switch k {
        case "name":
            f.Name = v.(string)
            break
        case "type":
            f.Type = v.(Output)
            break
        case "deprecationReason":
            f.DeprecationReason = v.(string)
            break
        case "description":
            f.Description = v.(string)
            break
        }
    }

    return nil
}

And I have this message:

panic: interface conversion: map[string]interface {} is not graphql.Output: missing method Description [recovered]
    panic: interface conversion: map[string]interface {} is not graphql.Output: missing method Description