从 API 返回响应作为内部 JSON 对象。

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

Return response from API as inner JSON objects

问题

以下是翻译后的内容:

// 使用这段代码获取国家的全名和ISO代码列表:

public Map<String, Object> getCountryNameCodeList() {

    String[] countryCodes = Locale.getISOCountries();
    Map<String, Object> list = new HashMap<>();

    for (String countryCode : countryCodes) {

        Locale obj = new Locale("", countryCode);

        list.put(obj.getDisplayCountry(), obj.getCountry());
    }

    return list;
}

// REST API:

@GetMapping("shipping_countries")
public ResponseEntity<Map<String, Object>> getShippingCountries() {

    Map<String, Object> originalMap = countriesService.getCountryNameCodeList();
    List<Map<String, Object>> modifiedList = new ArrayList<>();

    for (Map.Entry<String, Object> entry : originalMap.entrySet()) {
        Map<String, Object> countryData = new HashMap<>();
        countryData.put("name", entry.getKey());
        countryData.put("value", entry.getValue());
        modifiedList.add(countryData);
    }

    return new ResponseEntity<>(modifiedList, HttpStatus.OK);
}

希望上述修改的 Java 代码能够满足您的要求,将响应数据转换为所需的格式。

英文:

I use this code to get a list of countries as full name and ISO code:

public Map&lt;String, Object&gt; getCountryNameCodeList() {

        String[] countryCodes = Locale.getISOCountries();
        Map&lt;String, Object&gt; list = new HashMap&lt;&gt;();

        for (String countryCode : countryCodes) {

            Locale obj = new Locale(&quot;&quot;, countryCode);

            list.put(obj.getDisplayCountry().toString(), obj.getCountry());
        }

        return list;
    }

Rest API:

@GetMapping(&quot;shipping_countries&quot;)
public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; getShippingCountries() {

    return new ResponseEntity&lt;Map&lt;String, Object&gt;&gt;(countriesService.getCountryNameCodeList(), HttpStatus.OK);
}

I get the response data in this format:

{
    &quot;Papua New Guinea&quot;: &quot;PG&quot;,
    &quot;Cambodia&quot;: &quot;KH&quot;,
    &quot;Kazakhstan&quot;: &quot;KZ&quot;,
    &quot;Paraguay&quot;: &quot;PY&quot;,
    .....
}

I would like to get the data this way:

[
  {
    name: &quot;Papua New Guinea&quot;,
    value: &quot;PG&quot;
  },
  {
    name: &quot;Unites States&quot;,
    value: &quot;US&quot;
  }, 
  ....
]

How I can modify the Java code to return the data this way?

答案1

得分: 3

尝试这个方法。您需要使用数据传输对象来返回定制的数据。

创建一个DTO类。

public class DTO {

    private String key;
    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "DTO [key=" + key + ", value=" + value + "]";
    }

}

在控制器中创建REST API。示例:

@RestController
public class Sample {

    @RequestMapping("shipping_countries")
    public ResponseEntity<List<DTO>> getShippingCountries() {
        Map<String, String> map = new HashMap<>();
        map.put("Papua New Guinea", "PG");
        map.put("Cambodia", "KH");
        List<DTO> list = getCustomisedData(map);
        return ResponseEntity.ok(list);
    }

    private List<DTO> getCustomisedData(Map<String, String> map) {
        List<DTO> dtos = new ArrayList();
        for (Entry<String, String> value : map.entrySet()) {
            DTO dto = new DTO();
            dto.setKey(value.getKey());
            dto.setValue(value.getValue());
            dtos.add(dto);
        }
        return dtos;
    }
}

输出:

从 API 返回响应作为内部 JSON 对象。

英文:

Try this approach. You need to use data transfer object to return customized data.

Create a class DTO.

public class DTO {

	private String key;
	private String value;

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return &quot;DTO [key=&quot; + key + &quot;, value=&quot; + value + &quot;]&quot;;
	}

}

Create Rest API in the controller. Example :

@RestController
public class Sample {

	@RequestMapping(&quot;shipping_countries&quot;)
	public ResponseEntity&lt;List&lt;DTO&gt;&gt; getShippingCountries() {
		Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
		map.put(&quot;Papua New Guinea&quot;, &quot;PG&quot;);
		map.put(&quot;Cambodia&quot;, &quot;KH&quot;);
		List&lt;DTO&gt; list = getCustomisedData(map);
		return ResponseEntity.ok(list);
	}

	private List&lt;DTO&gt; getCustomisedData(Map&lt;String, String&gt; map) {
		List&lt;DTO&gt; dtos = new ArrayList();
		for(Entry&lt;String, String&gt; value: map.entrySet()) {
			DTO dto = new DTO();
			dto.setKey(value.getKey());
			dto.setValue(value.getValue());
			dtos.add(dto);
		}
		return dtos;
	}
}

Output :

从 API 返回响应作为内部 JSON 对象。

答案2

得分: 2

收到的响应是一个地图(map)的JSON表示,这也是你返回的内容。

如果你想要的json是一个对象数组,那么如果你想要返回它,最简单的方法就是以这种方式返回,就是从你的地图返回Map.Entry的集合。类似这样:

@GetMapping("shipping_countries")
public ResponseEntity<Set<Map.Entry<String, Object>>> getShippingCountries() {

    return new ResponseEntity<>(countriesService.getCountryNameCodeList().entrySet(), HttpStatus.OK);
}

另一种方法是为响应创建一个Json序列化器,但这似乎有点过度设计。

英文:

The response you are getting is the JSON representation of a map, which is what you return.
The json you want is an array of objects, so if you want to return that- the easiest way will be to return it like that, is to return the set of Map.Entry from your map. Something like that:

@GetMapping(&quot;shipping_countries&quot;)
public ResponseEntity&lt;Set&lt;Map.Entry&lt;String, Object&gt;&gt;&gt; getShippingCountries() {

    return new ResponseEntity&lt;&gt;(countriesService.getCountryNameCodeList().entrySet(), HttpStatus.OK);
}

Other way can be to create a Json serializer for the response, but it seems like an overkill

huangapple
  • 本文由 发表于 2020年10月3日 19:23:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64183667.html
匿名

发表评论

匿名网友

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

确定