如何将 JsonObject 对象转换为另一种对象类型的列表

huangapple go评论108阅读模式
英文:

How to convert a JsonObject object to a list of another object type

问题

我有一个将返回类似以下内容的对象列表的服务:

{
    "myobject": [
        {
            "first": "10",
            "second": 5.000
        },
        {
            "first": "20",
            "second": 20.000
        },
        {
            "first": "30",
            "second": 50.000
        }
    ]
}

我使用以下请求获取此对象:

public String getMyObject() {
    String url = UriComponentsBuilder.fromHttpUrl(myUrl);
    ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
    return response.getBody();
}

我需要将此列表放入此类型的对象列表中:

@Getter
@Setter
public class MyObject {
    private String firstParam;
    private String secondParam;
}

如何实现?有人可以帮助我吗?

英文:

I have a service that will return a list of objects something like this:

{
      &quot;myobject&quot;: [
        {
          &quot;first&quot; : &quot;10&quot;,
          &quot;second&quot;: 5.000
        },
        {
          &quot;first&quot; : &quot;20&quot;,
          &quot;second&quot;: 20.000
        },
        {
          &quot;first&quot; : &quot;30&quot;,
          &quot;second&quot;: 50.000
        }
      ]
    }

I take this object with this request

public String getMyObject() {

	String url = UriComponentsBuilder.fromHttpUrl(myUrl);
	ResponseEntity&lt;String&gt; response = restTemplate.getForEntity(url, String.class);
	return response.getBody();
}

I need to put this list inside a list of Objects of this type:

@Getter
@Setter
public class MyObject{
	
	private String firstParam
	private String secondParam

}

How to do this? Can anybody help me?

答案1

得分: 0

这里的主要问题是您在这行代码中期望的响应对象是什么:

ResponseEntity&lt;myObject[]&gt; response = restTemplate.getForEntity(url , myObject[].class);

相反,您应该请求一个 MyDTO 对象,因为您的控制器也在返回一个 MyDTO 对象:

ResponseEntity&lt;MyDTO&gt; response = restTemplate.getForEntity(url , MyDTO.class);

然后通过从 ResponseEntity 响应对象中提取 MyDTO 对象,在提取 MyDTO 对象后使用以下代码来检索列表:

List&lt;MyObject&gt; myList = myDTO.getMyObject();

英文:

The main problem here is what you expect as a response object at this line:

ResponseEntity&lt;myObject[]&gt; response = restTemplate.getForEntity(url , myObject[].class);

Instead you should ask for a MyDTO object since also your controller is returning a MyDTO object:

ResponseEntity&lt;MyDTO&gt; response = restTemplate.getForEntity(url , MyDTO.class);

and retrieving the list with a

List&lt;MyObject&gt; myList = myDTO.getMyObject();

after extracting the MyDTO object from the ResponseEntity response object.

huangapple
  • 本文由 发表于 2020年10月27日 22:47:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64556932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定