[英]How to get the first data object of a data object (REST api)
I Have a REST api that contains the data like this way我有一个包含这样数据的 REST api
{
...
... //<- more data here
...
"currencies": {
"BTN": {
"name": "Bhutanese ngultrum",
"symbol": "Nu."
},
"INR": {
"name": "Indian rupee",
"symbol": "₹"
}
}
...
... //<- more data here
...
}
i am doing a project in java where i need to use okhttp and show information about a country from an available rest api and before when i used this api it had all the data in currencies in an data array and that was helpful as you can just get the first zero object from the array , but after they updated the api they made all data in currencies an object and i only want the first object , any way i can get it?我正在用 java 做一个项目,我需要使用 okhttp 并从可用的休息 api 显示有关国家的信息,在我使用这个 api 之前,它在数据数组中包含所有货币数据,这很有帮助,因为你可以从数组中获取第一个零对象,但是在他们更新 api 后,他们将货币中的所有数据都设为一个对象,而我只想要第一个对象,有什么办法可以得到它?
OK, so you have two options here ...好的,所以你在这里有两个选择......
Option 1. Create two classes like this and use ObjectMapper
class to do automatic deserealisation for you.选项 1.创建两个这样的类,并使用
ObjectMapper
类为您进行自动去实化。
class CurrencyData {
String name;
String symbol;
}
class CurrencyJsonResponse {
CurrencyData INR;
CurrencyData BTN;
}
public static void main(String[] args) {
OkHttpClient client = // build an instance;
ObjectMapper objectMapper = new ObjectMapper();
ResponseBody responseBody = client.newCall(request).execute().body();
CurrencyJsonResponse currencyResponse = objectMapper.readValue(responseBody.string(), CurrencyJsonResponse.class);
//Get data by using getters on currencyResponse object
}
Option 2 You can write a custom deserealizer by extending the StdDeserializer<T>
class.选项 2您可以通过扩展
StdDeserializer<T>
类来编写自定义反实现器。 You'll have to programmatically inspect the JsonNode
parse tree and assemble the object that you want.您必须以编程方式检查
JsonNode
解析树并组装所需的对象。
This article explains how to do it and comes with a working code sample这篇文章解释了如何做到这一点,并附带了一个工作代码示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.