如何从远程api序列化制作对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从远程api序列化制作对象相关的知识,希望对你有一定的参考价值。

我目前正在进行第一次使用服务来处理网络操作的练习。我的第一个应用程序想法涉及使用YahooFinanceApi https://financequotes-api.com/#singlestock-hist获取具有一些历史记录的股票报价我目前的问题是将对象(股票)返回到要显示的游戏活动。我已经明白我需要使用serializable或parcelable但是因为我只想使用它一次我认为可序列化需要更少的编码。然而,putExtra似乎并没有把我称之为stockInfo的Stock变量视为我可以转移的东西。任何人都可以帮我理解我做错了什么。

StockPul​​lService文件编写如下。

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import java.io.IOException;
import java.util.Calendar;

import yahoofinance.Stock;
import yahoofinance.YahooFinance;
import yahoofinance.histquotes.Interval;
import static android.content.ContentValues.TAG;

public class StockPullService extends IntentService {

    public static final String TICKER = "ticker";

    public StockPullService() {
        super("StockPullService");
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {

        Log.d(TAG, "Service Started");
        if(workIntent != null) {
            int toMonth = (int) (-1 * Math.ceil(Math.random() * 100)); //Randomises what month to end on a

            Calendar from = Calendar.getInstance(); //Makes a calendar from point
            Calendar to = Calendar.getInstance(); //Makes a calendar to point
             from.add(Calendar.MONTH, toMonth - 5); //From a random number of months ago
             to.add(Calendar.MONTH, toMonth); //To 5 months later (To accomodate     for 20 weeks of guesses)

            try {
                Stock stockInfo = YahooFinance.get(workIntent.getStringExtra(TICKER), from, to, Interval.WEEKLY);
                 Log.d(TAG, "Service Successful");
            } catch (IOException e) {
                Log.d(TAG, "Service Failed");
                e.printStackTrace();
            }

            Intent intentResponse = new Intent();
            intentResponse.addCategory(Intent.CATEGORY_DEFAULT);
            intentResponse.putExtra("FetchedStock", stockInfo);
            Log.d(TAG, "Service Completed");
        }

    }
}

游戏活动如下。

公共类GameActivity扩展Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    Intent intent = new Intent(getApplicationContext(), StockPullService.class);
    intent.putExtra(StockPullService.TICKER, "HM-B.ST");
    startService(intent);

    Stock stock = (Stock) getIntent().getSerializableExtra("FetchedStock");
}

}

答案

您可以为Stock创建一个可序列化的包装器,如下所示:

public class SerializableStock implements Serializable {

    private static final long serialVersionUID = 1L;

    private Stock stock;

    public SerializableStock(final Stock stock) {
        this.stock = stock;
    }

    public Stock getStock() {
        return this.stock;
    }

    private void writeObject(java.io.ObjectOutputStream stream)
        throws IOException {
        stream.writeObject(stock.getSymbol());
        stream.writeObject(stock.getName());
        // TODO: serialize the rest of the fields
    }

    private void readObject(java.io.ObjectInputStream stream)
        throws IOException, ClassNotFoundException {
        this.stock = new Stock((String) stream.readObject());
        this.stock.setName((String) stream.readObject();
        // TODO: deserialize and set the rest of the fields
    }
}

StockPullService中序列化之前将其换行:

@Override
protected void onHandleIntent(Intent workIntent) {
    ...
    intentResponse.putExtra("FetchedStock", new SerializableStock(stockInfo));
    ...
}

并解开它GameActivity类:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    Stock stock = ((SerializableStock) getIntent().getSerializableExtra("FetchedStock")).getStock();
}

以上是关于如何从远程api序列化制作对象的主要内容,如果未能解决你的问题,请参考以下文章

将 Google API 客户端对象从活动传递到滑动选项卡片段

如何将 JSON 返回反序列化为从 RestSharp 调用到 API 的对象数组?

如何将库类或对象传递给片段?

教程4 - 验证和权限

从api逻辑任务和反序列化对象并反序列化json

如何从 PHP 中获取远程 JSON 或 XML API 数据并将返回对象分配为 PHP 变量?