首页 \ 问答 \ Golang打印地图内部由json.NewDecoder生成的地图(Golang print map inside map generated by json.NewDecoder)

Golang打印地图内部由json.NewDecoder生成的地图(Golang print map inside map generated by json.NewDecoder)

我正在使用这里的答案从api中获取一些json:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "net/http"
)

func main() {
   resp, err := http.Get("http://api.openweathermap.org/data/2.5/forecast?id=524901&appid=1234")
   if err != nil {
      log.Fatal(err)
   }
   var generic map[string]interface{}
   err = json.NewDecoder(resp.Body).Decode(&generic)
   if err != nil {
      log.Fatal(err)
   }
   fmt.Println(generic)
}

它正在工作,我有一个存储在generic变量中的json映射。

当我打印时:

fmt.Println(generic["city"])

我回来了:

map[id:524901 name:Moscow coord:map[lon:37.615555 lat:55.75222] country:RU population:0 sys:map[population:0]]

现在我想访问城市名称。 我正在尝试以下方法:

fmt.Println(generic["city"]["name"])

我得到错误:

muxTest / router.go:30:无效操作:generic [“city”] [“name”](类型interface {}不支持索引)

还尝试了generic["city"].name不起作用。

如何访问城市名称值?


I'm using the answer here to fetch some json from an api:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "net/http"
)

func main() {
   resp, err := http.Get("http://api.openweathermap.org/data/2.5/forecast?id=524901&appid=1234")
   if err != nil {
      log.Fatal(err)
   }
   var generic map[string]interface{}
   err = json.NewDecoder(resp.Body).Decode(&generic)
   if err != nil {
      log.Fatal(err)
   }
   fmt.Println(generic)
}

It's working, I have a map of the json stored in the generic variable.

When I print with:

fmt.Println(generic["city"])

I get back:

map[id:524901 name:Moscow coord:map[lon:37.615555 lat:55.75222] country:RU population:0 sys:map[population:0]]

Now I want to access the city name. I'm trying the following:

fmt.Println(generic["city"]["name"])

And I get error:

muxTest/router.go:30: invalid operation: generic["city"]["name"] (type interface {} does not support indexing)

Also tried generic["city"].name which didn't work.

How can I access the city name value?


原文:https://stackoverflow.com/questions/41885456
更新时间:2024-04-02 09:04

最满意答案

另一种选择是使用@PostLoad 过滤器

所以这将是这样的:

@Root(name = "message")
@XmlRootElement
@Entity
@Table(name="app_messages")
public class MessageBean implements Serializable, DataModel {
....

@PostLoad
public void deleteSensitiveData() {
   this.password = null;
}
}

Another option is to use @PostLoad filters.

So this will be something like this:

@Root(name = "message")
@XmlRootElement
@Entity
@Table(name="app_messages")
public class MessageBean implements Serializable, DataModel {
....

@PostLoad
public void deleteSensitiveData() {
   this.password = null;
}
}

相关问答

更多
  • 尝试这个: List list = (List) session.createQuery("FROM Project p JOIN p.contentManager").list(); List result = new ArrayList(); for(int i = 0; i < list.size(); i++) { Object[] row = (Object[]) list.get(i); Project p = (Proje ...
  • 您可以通过Assets类中的@NamedQuery来完成它: select a from Asserts a where a.location.site.contry.regin.reginName = :reginName 希望有所帮助 You can just complete it by a @NamedQuery in the class Assets : select a from Asserts a where a.location.site.contry.regin.reginName = : ...
  • 将它们标记为@Transient 。 Mark them as @Transient.
  • 在JPQL / HQL中,您不需要为连接指定ON子句,因为Hibernate已经知道两个实体之间的映射以及生成所述连接所需的列。 所以你只需要提供执行连接的谓词和请求,如下所示 SELECT u FROM User u JOIN u.roles ur WHERE u.username = :username AND u.password = :password AND ur.userRole = :role In JPQL / HQL you do not need to specif ...
  • Hibernate文档说: Hibernate不支持在同一根元素下混合映射。 通过组合元素,可以将每个层次结构的表和每个子类策略的表混合在同一个 元素下 在您的情况下,您将需要将discriminator列移动到tperson表并使用join元素为您的学生类添加额外的属性。
    这是数据库模式的一个问题: 您试图将3个单独的关联(图像集合,图像属性,集合属性) 填充到单个ImageCollection表中。 这不是一件好事。 虽然使用普通的SQL可能会让这种情况变得很糟糕(代价是大量的表中有空列的行),但您无法在Hibernate中正确映射它。 顺便说一句,这个表不需要代理主键。 你需要做的是将其分成3个独立的表格,并将你的模型映射为Hibernate中适当的多对多。 例如: @Entity public class Image { @ManyToMany @JoinTab ...
  • 而不是试图去做 from Member m join m.family f where f.name = ? 这是不可能的,你可以做相反的事情 select m from Family f join f.members m where f.name = ? 我知道,这是HQL而不是Criteria,但这就是我更流利的。 尽管把这个HQL翻译成标准应该是微不足道的。 thank you guys, I have resolved this with one of my colleague as under ...
  • 另一种选择是使用@PostLoad 过滤器 。 所以这将是这样的: @Root(name = "message") @XmlRootElement @Entity @Table(name="app_messages") public class MessageBean implements Serializable, DataModel { .... @PostLoad public void deleteSensitiveData() { this.password = null; } } An ...
  • 对于您可以使用的Parent类 @JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT a.id FROM Child c WHERE c.child_id=child_id ...
  • 您必须将映射注释放置在实体中的位置保持一致。 要么把它们全部放在吸气剂上,要么将它们全部放在田地上。 既然你把getter的Id注释,但是字段上的ManyToOne注释,那么Hibernate会忽略ManyToOne。 请注意,映射没有多大意义:用于唯一标识内容的列也不能用于引用框。 并且box属性不能同时使用Column和JoinColumn注释。 它是JoinColumn,而不是Column。 You must be consistent in where you place the mapping a ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)