dsvs50005 2017-12-12 07:29
浏览 590

在golang中构造复杂的JSON解析

I have a valid JSON, which I don't know how to parse in json.Unmarshal (golang):

{
   "method": "notice",
   "params": [0, [{
           "previous": "12345",
           "timestamp": "2017-12-12T05:49:09",
           "witness": "12345",
           "transaction_merkle_root": "ffff",
           "extensions": [],
           "witness_signature": "12345"
   }]]
}

All I can do is:

type MyJSON struct {
    Method string        `json:"method"`
    Params []interface{} `json:"params"`
}

I will be really thankful if somebody help me to write correct MyJSON type to parse all other fields through golang's json.Unmarshal. It's way too complex to me :(

  • 写回答

2条回答 默认 最新

  • douju1280 2017-12-12 08:04
    关注

    I assume that params depends on the method. If so, start by decoding the top-level to a struct with the method name and a json.RawMessage to collect the parameters as JSON text.

    var call struct {
        Method string
        Params json.RawMessage
    }
    if err := json.Unmarshal(data, &call); err != nil {
        log.Fatal(err)
    }
    

    Declare variables for each parameter. This code will depend on the method.

        var param0 int
        var param1 []struct {
            Previous                string
            Timestamp               string
            Witness                 string
            Transaction_merkle_root string
            Extensions              []interface{}
            Witness_signature       string
        }
    

    Create a parameter list using pointers to those variables.

        params := []interface{}{&param0, &param1}
    

    Now unmarshal the JSON to params. This will set the variables param0 and param1:

        if err := json.Unmarshal(call.Params, &params); err != nil {
            log.Fatal(err)
        }
    

    Repeat for other methods.

    Here's the runnable code on the playground.

    This can be simplified if you will only need to handle the "notice" method. In this case, you can decode directly to the parameters without the RawMessage step.

    var param0 int
    var param1 []struct {
        Previous                string
        Timestamp               string
        Witness                 string
        Transaction_merkle_root string
        Extensions              []interface{}
        Witness_signature       string
    }
    call := struct {
        Method string
        Params []interface{}
    }{
        Params: []interface{}{&param0, &param1},
    }
    
    if err := json.Unmarshal(data, &call); err != nil {
        log.Fatal(err)
    }
    

    Here's runnable code for the simple case.

    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试