如何谷歌GSON库可以用来解析JSON下面给出的 [英] How google gson library can be used to parse given below json

查看:96
本文介绍了如何谷歌GSON库可以用来解析JSON下面给出的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JSON

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

和样本模型类别

  public class Product 
{
private int productId;
私人字符串名称;

//产品ID和名称字段的getter和setter
}

如何将以上json数据存储在Product类中?我应该使用一个数组还是 ArrayList 来获得产品类,以及如何使用Google Gson库?

解决方案

您需要使用 TypeToken Map< Integer,Product> c>指定通用类型。这里有一些工作代码:

  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 b $ b {
private int productId;
私人字符串名称;

@Override
public String toString(){
return String.format(Product [productId =%s,name =%s],productId,name);
}
}
}


I have this JSON

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

and Sample Model Class is

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

   // getter and setter for productId and name fields
}

How can I store above json data in Product class? Should I use an array or ArrayList for Product Class and how do I it using Google Gson library ?

解决方案

You need parse the whole JSON string as a Map<Integer, Product>, using TypeToken to specify the generic type. Here's some working code:

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);
    }     
  }
}

这篇关于如何谷歌GSON库可以用来解析JSON下面给出的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆