import java.lang.reflect.Type; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class Json解析成List { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(" {‘name‘:‘张辽‘,‘power‘:93},"); sb.append(" {‘name‘:‘徐晃‘,‘power‘:94},"); sb.append(" {‘name‘:‘张郃‘,‘power‘:91},"); sb.append(" {‘name‘:‘于禁‘,‘power‘:90},"); sb.append(" {‘name‘:‘乐进‘,‘power‘:87}"); sb.append("]"); String json = sb.toString(); Gson gson = new Gson(); // 将 json 转化成List泛型 Type t = new TypeToken<List<People>>() {}.getType(); List<People> ps = gson.fromJson(json, t); System.out.println(ps); System.out.println(ps.get(1).getName() + "," + ps.get(1).getPower()); } }
运行结果:
[[email protected], [email protected], [email protected], [email protected], [email protected]]
徐晃,94
import java.util.Map; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class Json解析成map { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append(" ‘锦马超‘:{‘name‘:‘马超‘,‘Power‘:96},"); sb.append(" ‘猛张飞‘:{‘name‘:‘张飞‘,‘Power‘:96}"); sb.append("}"); String json = sb.toString(); Gson gson = new Gson(); // 将json转化成 Map泛型 Type t = new TypeToken<Map<String, People>>() { }.getType(); Map<String, People> map = gson.fromJson(json, t); System.out.println(map); } }
运行结果:
{锦马超[email protected], 猛张飞[email protected]}
辅助类:
public class People { private String name; private int power; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPower() { return power; } public void setPower(int power) { this.power = power; } }
时间: 2024-10-14 00:36:22