当我们通过Gson获取多个对象中的相同字段对应的值时,可以通过以下方式获取每个字段的值

public class IndexTest {

/**

 * 首先,我们需要依次获取我们需要的字段对应的值

 * 我们每获取一次就需要将索引往后移动一次,

 * 当我们获取的值不存在时结束

 * @param str

 * @param key

 * @return

 */

public List<String> getStrList(String str, String key) {

List<String> list = new ArrayList<String>();

int index = 0;

while((index = str.indexOf(key, index)) != -1) {

list.add(str.substring(index + key.length() + 1, str.indexOf(",", index)));

index += key.length();

}

return list;

}

@Test

public void test() {

String str = "id:1001, name:张三, age:20; id:1002, name:李四, age:19; id:1021, name:陈琦, age:39 ";

List<String> strList = getStrList(str, "name");

for (String string : strList) {

System.out.println(string);

}

}


}