Ability to unmarshal query response directly to protobuf struct

Moved from GitHub dgo/8

Posted by lehajam:

I would like to know if there is a way to unmarshal a query response directly into a protobuf struct (the same used to insert data). In the code below it will only work if I create a new struct and define contract field as an array.
This was previously possible using client.unmarshal and I believe being able to insert and query data from dgraph via grpc and protobuf (without any additional code) was a great feature of the go client.

// PB definition
//
// message European {
// 	double timestamp = 1;
// 	string ticker = 2;
// 	string undticker = 3;
// 	double strike = 4;
// 	double expiry = 5;
// 	string putcall = 6;
// }
//
// message PriceRequest {
// 	double pricingdate = 1;
// 	European contract = 2;
// 	OptionMarket marketdata = 3;
// }

func Test_contractRequest(t *testing.T) {
	resp := query(
		`query ContractRequest($optionTicker: string){
			contract(func: eq(ticker, $optionTicker)){
				ticker
				strike
				undticker
				expiry
				putcall
			}
		}`,
		map[string]string{
			"$optionTicker": "AAPL DEC2017 PUT",
		})

	priceReq := &pb.PriceRequest{}
	// Fails with error "json: cannot unmarshal array into Go struct field PriceRequest.contract of type pb.European"
	err := json.Unmarshal(resp.GetJson(), priceReq)
	if err != nil {
		type Root struct {
			Contract []pb.European `json:"contract"`
		}

		root := &Root{}
		// Works fine
		err = json.Unmarshal(resp.GetJson(), root)
		if err != nil {
			t.Error(err)
		}
		t.Log(root)
		t.Fail()
	}
	t.Log(priceReq)
}

manishrjain commented :

You could annotate protobufs with JSON tags, I think, which can then be used to parse directly from JSON byte array. Otherwise, you could create Go structs, with the JSON tags, parse into the Go struct, and then “transfer” over into the PBs.

We had a complicated way to parse responses directly into protobufs, but we got rid of that in favor of JSON, which works for most users. Direct protobuf parsing is not coming back.