通过spring boot读取JSON映射结构 [英] Reading JSON map structure via spring boot

查看:336
本文介绍了通过spring boot读取JSON映射结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的REST服务返回以下JSON结构:

If I have the following JSON structure returned by my REST service:

{
   "foo" : {
      "id" : "baz"
   }
   "qux" : {
      "id" : "toto"
   }
}

对我而言,它看起来像一个地图结构。我不知道如何使用弹簧靴(通过杰克逊)阅读这篇文章。

To me it looks like a map structure. I am not sure how I can read this using spring boot (via Jackson).

我已经定义了我的JSON绑定类,如下所示:

I have defined my JSON bind class like so:

public class Foos {

   private Map<String, Foo> fooInstances;

   private void setFooInstances(Map<String, Foo> fooInstances) {
      this.fooInstances = fooInstances;
   }

   private Map<String, Foo> getFooInstances() {
      return fooInstances;
   }

}

并且Foo实例看起来像这样:

And a Foo instance looks like so:

public class Foo {

   private String id;


   private void setId(String id) {
      this.id = id;
   }

   private String getId() {
      return id;
   }

}

发出请求的弹簧代码是这样的:

The spring code for making the request is like so:

RestTemplate template = new RestTemplate();
ResponseEntity<Foos> responseEntity = (ResponseEntity<Foos>) template.getForEntity(serviceEndpointURL, Foos.class);

我最初有一个START_OBJECT错误,我通过创建带有相应地图的Foos类来解决这个错误,现在我不要收到错误。相反,我得到一个填充的ResponseEntity,带有'Foos'实例,但地图为空。知道我做错了什么吗?

I originally had a START_OBJECT error which I fixed by creating the Foos class with the corresponding map and now I don't get an error. Instead I get a populated ResponseEntity, with a 'Foos' instance, but the map is null. Any idea what I am doing wrong?

推荐答案

像这样修改你的Foos课程

Modify your Foos class like this

public class Foos {

@JsonIgnore
private Map<String, Object> properties = new HashMap<String, Object>();

@JsonAnyGetter
public Map<String, Object> getProperties() {
return this.properties;
}

@JsonAnySetter
public void setProperty(String name, Object value) {
this.properties.put(name, value);
}
}

您可以从对象进行类型转换从地图到 Foo

如果您有任何疑问,请告诉我! !

Let me know if you have any questions!!

这篇关于通过spring boot读取JSON映射结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆