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 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错