在 Java 中使用 GSON 反序列化 json

Deserializing json with GSON in Java

我有Json

{"0x3b198e26e473b8fab2085b37978e36c9de5d7f68":{"usd":541.56},"0x54523d5fb56803bac758e8b10b321748a77ae9e9":{"usd":0.059097},"0x330540a9d998442dcbc396165d3ddc5052077bb1":{"usd":1.649e-09}}

接下来,我正在使用 gson 尝试将 json 转换为价格对象

        RequestEntity requestEntity = new RequestEntity(requestHeaders, HttpMethod.valueOf("GET"), uri);
        restTemplate.exchange(requestEntity, String.class);
        ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
        String response = responseEntity.getBody();
        System.out.println(response);

        Gson gson = new Gson();
        Price price = gson.fromJson(response, Price.class);

Price.java

  public class Price {
        private Wallet wallet;
        private Wallet token;
        private Wallet contract;
    
        public Wallet getWallet() {
            return wallet;
        }
    
        public void setWallet(Wallet wallet) {
            this.wallet = wallet;
        }
    
        public Wallet getToken() {
            return token;
        }
    
        public void setToken(Wallet token) {
            this.token = token;
        }
    
        public Wallet getContract() {
            return contract;
        }
    
        public void setContract(Wallet contract) {
            this.contract = contract;
        }
    }

Wallet.java

public class Wallet {
    private Currencies currencies;

    public Currencies getCurrencies() {
        return currencies;
    }

    public void setCurrencies(Currencies currencies) {
        this.currencies = currencies;
    }
}

Currencies.java

public class Currencies {
    String currency;
    Integer value;

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }
}

我需要命名 class 字段“0x3b198e26e473b8fab2085b37978e36c9de5d7f68”、“0x54523d5fb56803bac758e8b10b321748a77ae9e92”和“ 0x330540a9d998442dcbc396165d3dbb150”?如果是,则这些名称无效。

否则我在调用时得到null

        System.out.println(price.getWallet());

我希望你能在这里使用自定义反序列化器

像这样为 Gson 注册它们:

GsonBuilder gsonBldr = new GsonBuilder();
gsonBldr.registerTypeAdapter(Price.class, new PriceCustomDeserializer());
gsonBldr.registerTypeAdapter(Wallet.class, new WalletCustomDeserializer());
gsonBldr.registerTypeAdapter(Currencies.class, new CurrenciesCustomDeserializer());

和反序列化器实现:

public class PriceCustomDeserializer implements JsonDeserializer<Price> {

    @Override
    public Price deserialize
      (JsonElement jElement, Type typeOfT, JsonDeserializationContext context) 
      throws JsonParseException {
        JsonObject jObject = jElement.getAsJsonObject();
        //parse 3 values (without names) from json by order 
    }
}

//add remaining 2 deserializers