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

后端 未结 2 721
盖世英雄少女心
盖世英雄少女心 2021-01-22 23:10

I have this JSON

{
    \"309\":{ \"productId\":309,  \"name\":\"Heat Gear Polo\"},
    \"315\":{ \"productId\":310,  \"name\":\"Nike\"},
    \"410\":{ \"productI         


        
2条回答
  •  悲哀的现实
    2021-01-23 00:02

    You need parse the whole JSON string as a Map, 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>(){}.getType();
        Map 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);
        }     
      }
    }
    

提交回复
热议问题