简体   繁体   English

从 JSON 生成不同的 Java 对象 API 响应使用 Jackson

[英]Generate different Java Objects from JSON API Response using Jackson

I'm working on a project at the moment that requires me to take in a various currency pairs and generate a response object from an API call response.我目前正在做一个项目,需要我接受各种货币对并从 API 调用响应生成响应 object。 I'm using jackson to map the JSON response to java objects then reading data from an ArrayList generated.我正在使用 jackson 到 map JSON 对 java 对象的响应,然后从生成的 ArrayList 中读取数据。 The problem is the JSON response can have the different currency pairing strings as a key for the list of pairing data.问题是 JSON 响应可以将不同的货币配对字符串作为配对数据列表的键。 Here's what a typical response looks like:以下是典型的响应:

{"error":[],"result":{"XXBTZUSD":[[1647062100,"39091.2","39184.9","39088.9","39139.0","39150.9","59.22447291",161],}[1647063000,"39138.9","39188.4","39138.9","39151.2","39174.2","2.92905848",126]]}

The problem arises when I try to pull data from a different currency pair as my result object is hard coded to pull the data for the JSON key XXBTZUSD.当我尝试从不同的货币对提取数据时出现问题,因为我的结果 object 被硬编码为提取 JSON 密钥 XXBTZUSD 的数据。 Here's what my result object looks like:这是我的结果 object 的样子:

    public class Result{
    
        @JsonProperty("XXBTZUSD")
        public ArrayList<ArrayList<Object>> candles;
        public int last;
    }

I was thinking having the @JsonProperty be variable and pass in the key from the json response to correct pull the currnecy pair I set it to, but JsonProperty needs to be a constant.我在考虑让 @JsonProperty 是可变的,并从 json 响应中传递密钥以正确拉出我设置的货币对,但 JsonProperty 需要是一个常量。 The only way around this I can see is to have a ton of different classes for each currency pair but that would be inefficient and take around 15 separate classes to do.我能看到的解决这个问题的唯一方法是为每个货币对设置大量不同的类,但这效率低下并且需要大约 15 个单独的类来完成。 I'm not too familiar with the jackson library.我不太熟悉 jackson 库。 If anyone has any ideas of how to solve this I would be greatly appreciative, I've been trying to figure out a way around this for awhile now.如果有人对如何解决这个问题有任何想法,我将不胜感激,一段时间以来,我一直在努力寻找解决方法。 Thank you!谢谢!

If keys can be different, one option is to use a Map .如果密钥可以不同,一种选择是使用Map Your Result class won't be needed, parse the result property into Map<String, Object> .您的Result class 将不需要,将结果属性解析为Map<String, Object> Then extract like this:然后像这样提取:

Map<String, Object> result = deserialize();
ArrayList<ArrayList<Object>> arrays = (ArrayList<ArrayList<Object>>) result.get("XXBTZUSD");

Just change property depending on which currency pair you need.只需根据您需要的货币对更改属性即可。

Another option is writing custom deserializer, in which to always put value in your candles field, regardless of how the property is named in json.另一种选择是编写自定义反序列化程序,其中始终将值放入candles字段,无论该属性在 json 中如何命名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM