dubbo.apache.org/dubbo-go/v3@v3.1.1/filter/generic/generalizer/gson.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package generalizer 19 20 import ( 21 "encoding/json" 22 "reflect" 23 "sync" 24 ) 25 26 import ( 27 hessian "github.com/apache/dubbo-go-hessian2" 28 29 "github.com/dubbogo/gost/log/logger" 30 31 perrors "github.com/pkg/errors" 32 ) 33 34 import ( 35 "dubbo.apache.org/dubbo-go/v3/protocol/dubbo/hessian2" 36 ) 37 38 var ( 39 jsonGeneralizer Generalizer 40 jsonGeneralizerOnce sync.Once 41 ) 42 43 func GetGsonGeneralizer() Generalizer { 44 jsonGeneralizerOnce.Do(func() { 45 jsonGeneralizer = &GsonGeneralizer{} 46 }) 47 return jsonGeneralizer 48 } 49 50 type GsonGeneralizer struct{} 51 52 func (GsonGeneralizer) Generalize(obj interface{}) (interface{}, error) { 53 newObj, ok := obj.(hessian.POJO) 54 if !ok { 55 return nil, perrors.Errorf("unexpected type of obj(=%T), wanted is hessian pojo", obj) 56 } 57 58 jsonbytes, err := json.Marshal(newObj) 59 if err != nil { 60 return nil, err 61 } 62 63 return string(jsonbytes), nil 64 } 65 66 func (GsonGeneralizer) Realize(obj interface{}, typ reflect.Type) (interface{}, error) { 67 jsonbytes, ok := obj.(string) 68 if !ok { 69 return nil, perrors.Errorf("unexpected type of obj(=%T), wanted is string", obj) 70 } 71 72 // create the target object 73 ret, ok := reflect.New(typ).Interface().(hessian.POJO) 74 if !ok { 75 return nil, perrors.Errorf("the type of obj(=%s) should be hessian pojo", typ) 76 } 77 78 err := json.Unmarshal([]byte(jsonbytes), ret) 79 if err != nil { 80 return nil, err 81 } 82 83 return ret, nil 84 } 85 86 func (GsonGeneralizer) GetType(obj interface{}) (typ string, err error) { 87 typ, err = hessian2.GetJavaName(obj) 88 // no error or error is not NilError 89 if err == nil || err != hessian2.NilError { 90 return 91 } 92 93 typ = "java.lang.Object" 94 if err == hessian2.NilError { 95 logger.Debugf("the type of nil object couldn't be inferred, use the default value(\"%s\")", typ) 96 return 97 } 98 99 logger.Debugf("the type of object(=%T) couldn't be recognized as a POJO, use the default value(\"%s\")", obj, typ) 100 return 101 }