在Java中使用GSON反序列化json

ev7lccsx  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(230)

我有Json

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

接下来,我将使用gson尝试将json转换为price对象

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

价格.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;
        }
    }

电子钱包.java

public class Wallet {
    private Currencies currencies;

    public Currencies getCurrencies() {
        return currencies;
    }

    public void setCurrencies(Currencies currencies) {
        this.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;
    }
}

我需要将类字段命名为“0x3b198e26e473b8fab2085b37978e36c9de5d7f68"、“0x54523d5fb56803bac758e8b10b321748a77ae9e9”和“0x330540a9d998442dcbc396165d3dbb150"。如果是这样,这些名称就不是有效名称。
否则,调用时将得到null

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

unguejic1#

我希望您可以在这里使用自定义反序列化器,
为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

相关问题