google gson 库如何用于解析下面给出的 json

How google gson library can be used to parse given below json

我有这个JSON

{
    "309":{ "productId":309,  "name":"Heat Gear Polo"},
    "315":{ "productId":310,  "name":"Nike"},
    "410":{ "productId":311,  "name":"Armani"}
}

并且示例模型 Class 是

public class Product
{
   private int productId;
   private String name;

   // getter and setter for productId and name fields
}

如何在产品 class 中存储以上 json 数据?我应该为产品 Class 使用数组还是 ArrayList 以及如何使用 Google Gson 库?

您需要将整个 JSON 字符串解析为 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);
    }     
  }
}
public static void main(String[] args)
{
    try
    {
        Gson gson = new Gson();

        String json = "{\"309\":{ \"productId\":309,  \"name\":\"Heat Gear Polo\"},\"315\":{ \"productId\":310,  \"name\":\"Nike\"},\"410\":{ \"productId\":311,  \"name\":\"Armani\"}}";
        Type type = new TypeToken<Map<String, Product>>(){}.getType();
        Map<String, Product> myMap = gson.fromJson(json, type);
        System.out.println(myMap);
    }
    catch (Exception e)
    {
        // TODO: handle exception
    }
}