dongmen9517 2017-08-04 07:34
浏览 39
已采纳

Go中通用的解决方案

I want to make a useful library for JSON responses. In Java I've this already. I started now new with Go and have no idea how to transform my Java code. I've read that Go doesn't have anything like generics, but how can I solve my problem?

I'm talking about the following part of code:

@Data
public class ServiceResult<T extends Serializable> implements Serializable {

    private ServiceResultStatus status;
    private String type;
    private T content;
    private String hash;
    private String destination;
    private HashMap<String, Metadata> metadata = new HashMap<>();

...

The idea of service-result is to provide an structural pattern for RESTful web services. If you need more information, here is the link to my repo on Github: https://github.com/Viascom/service-result

A service-result looks at the end like this:

{
  "status": "successful",
  "type": "ch.viascom.example.models.response.GetTasksResponse",
  "content": [
    {
      "id": "3e99c7fb-0ed7-11e7-a7a5-0050569c3e5a",
      "name": "Example Task"
    }
  ],
  "hash": "7bf9c04d1e9f8fe7995e4b8beeac1a4c830e7ea",
  "destination": "ch.viascom.example.handler.TaskHandler",
  "metadata": {

  }
}
  • 写回答

1条回答 默认 最新

  • douhezhang8932 2017-08-04 09:48
    关注

    You can add the json-mapping directly to the structure definition and use the encoder, decoder to marshal and unmarshal it. It's all built in and easier than in other languages, imho.

    type ServiceResponse struct {
        Value string`json:"nameInJsonResponse"`
    }
    

    here is a good example from the playground: https://play.golang.org/p/4L2wMVv7tW

    For your particular case it should be something like this:

    type ServiceResult struct {
        Status ServiceResultStatus`json:"status"`
        Type string`json:"type"`
        Hash string`json:"hash"`
        Destination string`json:"destination"`
        Metadata map[string]Metadata metadata`json:"metadata"`
    }
    
    type ExplizitServiceResult struct {
        ServiceResult
        Content SomeStruct`json:"content"`
    }
    

    https://play.golang.org/p/FFfiq6LxVt

    If you don't want to derive every user struct from the ServiceResult you can define the content as interface{} so every struct can be inserted. I've updated my example for this. Maybe this is the easiest solution to your problem. https://play.golang.org/p/LNgreqrnnw

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大