【问题标题】:How to read Response, different from methods used in pojo class from API in Android如何读取响应,与 Android 中 API 的 pojo 类中使用的方法不同
【发布时间】:2018-08-05 11:27:31
【问题描述】:

我只想发回一个在 POJO 类中没有定义的属性。 我的 POJO 类是这样的

public class PostData {

    @SerializedName("Token")
    @Expose
    private String token;
    @SerializedName("Amount")
    @Expose
    private Integer amount;
    @SerializedName("AuthID")
    @Expose
    private String authID;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amt) {
        this.amount = amt;
    }

    public String getAuthID(){return authID;}

    public void setAuthID(String authID){
        this.authID = authID;
    }

}

Amount,Token,AuthID 从客户端发送到 API。这里我使用 HTTP Cloud 函数作为 HTTP POST。我需要将 TransID 发送回客户端,这在 POJO 类中不存在。在客户端我需要读取响应并存储它。 这是我的云功能代码:

exports.Add = functions.https.onRequest((req,res)=>{
//var testPublicKey = [xxxxxxxxxxxxxxxxx]
var stripe = require("stripe")("stripe_key");

console.log("Token:"+req.body.Token)
console.log("Amount:"+req.body.Amount)

var tokenToCharge = req.body.Token;
const amountToCharge = req.body.Amount;
var authID = req.body.AuthID;
const databaseRef = admin.firestore();
const payer = databaseRef.collection('deyaPayUsers').doc(authID).collection('Wallet').doc(authID);
 const balance = payer.Usd
 stripe.charges.create({
amount : amountToCharge,
currency : "usd",
description : "charge created",
source : tokenToCharge,
}, function(err, charge) {
if(charge.status === "succeeded"){
var trans = databaseRef.runTransaction(t=>{
 return t.get(payer)
    .then(doc=>{
     var updatedBalance = doc.data().Usd + parseInt(charge.amount);
     t.update(payer,{Usd : updatedBalance});
    });//return close
 }).then(result=>{
 console.log('Transaction success!');
 }).catch(err=>{
 console.log('Transaction Failure:',err);
 });
 }
});
});//end of stripe create charge

【问题讨论】:

标签: android firebase retrofit2 google-cloud-functions


【解决方案1】:

您使用瞬态键在 pojo 类中添加一个字段是忽略一个值以发送 api 调用并获取客户端值。

    transient
    private String TransID;

并制作getter和setter方法。

【讨论】:

  • 你能解释一下吗
【解决方案2】:

您有什么理由不想在您的 POJO 类中为 TransID 创建一个变量?我了解您的 POJO 类与您的应用程序的客户端交互。因此,拥有 TransID 的变量(带有 getter 和 Setter)将使您更灵活地读取响应并根据需要存储它。

【讨论】:

    【解决方案3】:

    使用 Retrofit 读取响应有一个单独的类(这里是 PostData),它代表我们在后端服务请求时获得的 JSON 响应的输出。创建一个接口类并使用 @Method(GET, POST , DELETE 等;) 注释并将参数传递给方法。在客户端将参数传递给方法并通过调用您期望的参数的 getmethod 来获取响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多