我有这个JSON
{ "309":{ "productId":309, "name":"Heat Gear Polo"}, "315":{ "productId":310, "name":"Nike"}, "410":{ "productId":311, "name":"Armani"} }
样本模型类为
public class Product { private int productId; private String name; // getter and setter for productId and name fields }
如何在产品类中存储上述json数据?我应该使用数组还是ArrayList产品类?如何使用Google Gson库?
ArrayList
您需要将整个JSON字符串解析为Map<Integer, Product>,TypeToken用于指定通用类型。这是一些工作代码:
Map<Integer, Product>
TypeToken
import java.lang.reflect.Type; import java.util.Map; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; public class JsonTest { private static final String JSON = "{" + "\"309\":{ \"productId\":309, \"name\":\"Heat Gear Polo\"}," + "\"315\":{ \"productId\":310, \"name\":\"Nike\"},"+ "\"410\":{ \"productId\":311, \"name\":\"Armani\"}"+ "}"; public static void main(String... args) { Gson g = new Gson(); Type type = new TypeToken<Map<Integer, Product>>(){}.getType(); Map<Integer, Product> map = g.fromJson(JSON, type); System.out.println(map); } public static class Product { private int productId; private String name; @Override public String toString() { return String.format("Product [productId=%s, name=%s]", productId, name); } } }