Java 中从字符串提取 Address 对象的值
假设 hosDisList2 的值为 '[Address{city='北京市', district='朝阳区', detail='xx街道xx号'}, Address{city='上海市', district='浦东新区', detail='xx街道xx号'}]',要取出第一个 Address 的值,可以按照以下步骤:
- 首先将 hosDisList2 转换成一个 ArrayList 类型的对象,可以使用以下代码:
ArrayList<Address> addressList = new Gson().fromJson(hosDisList2, new TypeToken<ArrayList<Address>>(){}.getType());
需要引入以下依赖:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
- 然后就可以通过访问 ArrayList 的 get 方法来获取第一个 Address 对象,例如:
Address firstAddress = addressList.get(0);
- 最后就可以获取第一个 Address 的值了,例如:
String city = firstAddress.getCity();
String district = firstAddress.getDistrict();
String detail = firstAddress.getDetail();
原文地址: http://www.cveoy.top/t/topic/nVjx 著作权归作者所有。请勿转载和采集!