Gson将字符串转为List
2023-02-26 本文已影响0人
蚂蚁森林农夫
1.字符串转为List<Person>
List<Person> personList = gson.fromJson(json, new TypeToken<List<Person>>() {}.getType());
2.字符串转为List<Map<String,Object>>,且Map中有时间戳类型
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.internal.LinkedTreeMap;
Gson gson = new Gson();
List<Map<String,Object>> list = new ArrayList<>();
JsonParser parser = new JsonParser();
JsonArray jsonarray = parser.parse(jsonStr).getAsJsonArray();
for (JsonElement element : jsonarray) {
Map map = gson.fromJson(element, Map.class);
Double t = (double)map.get("timestamp");
BigDecimal timestamp = new BigDecimal(t);
map.put("timestamp",timestamp);
list.add(map);
}