dongluan1743 2016-12-12 02:28
浏览 32
已采纳

在结构映射中存储/解码json的最佳方法

I have a mapping inside a struct as follow :

type Red struct {
       **other 
       Tel map[string]string `json:"Tel"`
}

I receive my data json formated the following way

{
 "Params":[{"rewew": "tref"},{"Value": "x"},....]    
}

And i'm searching for the most effective way of populating my struct with the data so that

Tel["rewew"] = "tref"
Tel["Value"] = "x"

For the rest of the values it works fine when those are simplier values when doing this:

 var t Red
 decode := json.NewDecoder(req.Body)
 decode.Decode(&t)

But i'm having trouble with maps

  • 写回答

1条回答 默认 最新

  • dphnn333971 2016-12-12 02:45
    关注

    If your JSON is

    {
      "Params":[{"rewew": "tref"},{"Value": "x"},....]    
    }
    

    And if you want to map Params into Tel, your structure should be:

    type Red struct {
       **other 
       Tel []map[string]string `json:"Params"`
    }
    

    And you can add new elements like:

    red.Tel = append(red.Tel, map[string]string{"rewew": "tref"})
    red.Tel = append(red.Tel, map[string]string{"Value": "x"})
    

    But, I think there is a better way to do it if you're allowed to change the request AND the keys don't repeat themselves, using a JSON like

    {
      "Params":{"rewew": "tref", "Value": "x"}    
    }
    

    The struct should be:

    type Red struct {
       **other 
       Tel map[string]string `json:"Params"`
    }
    

    and you can use the data like:

    red.Tel["rewew"] = "tref"
    red.Tel["Value"] = "x"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化