小编典典

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

java

我有这个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库?


阅读 241

收藏
2020-11-26

共1个答案

小编典典

您需要将整个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);
    }     
  }
}
2020-11-26