我一直在尝试使用GSON和JsonScheme2Pojo映射我的json对象。
到目前为止,我已经创建了这个类。
public class MPayTransaction {
@SerializedName("mp_request_type")
@Expose
private String mpRequestType;
@SerializedName("status_code")
@Expose
private String statusCode;
@SerializedName("amount")
@Expose
private String amount;
@SerializedName("chksum")
@Expose
private String chksum;
@SerializedName("pInstruction")
/**
*
* @return
* The mpRequestType
*/
public String getMpRequestType() {
return mpRequestType;
}
/**
*
* @param mpRequestType
* The mp_request_type
*/
public void setMpRequestType(String mpRequestType) {
this.mpRequestType = mpRequestType;
}
/**
*
* @return
* The statusCode
*/
public String getStatusCode() {
return statusCode;
}
/**
*
* @param statusCode
* The status_code
*/
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
/**
*
* @return
* The amount
*/
public String getAmount() {
return amount;
}
/**
*
* @param amount
* The amount
*/
public void setAmount(String amount) {
this.amount = amount;
}
/**
*
* @return
* The chksum
*/
public String getChksum() {
return chksum;
}
/**
*
* @param chksum
* The chksum
*/
public void setChksum(String chksum) {
this.chksum = chksum;
}
/**
*
* @return
* The pInstruction
*/
public int getPInstruction() {
return pInstruction;
}
/**
*
* @param pInstruction
* The pInstruction
*/
public void setPInstruction(int pInstruction) {
this.pInstruction = pInstruction;
}
}
然后我用这种方式调用了这个类:
Gson gson = new Gson();
MPayTransaction mPayTransaction = gson.fromJson(jsonString, MPayTransaction.class);
这是有效的,我只需要调用例如MPayTransaction.getAmount()
来获取金额的值;
我一直想知道,如何映射多个json对象?让我们说以前的json字符串是这样的:
{
"mp_request_type": "donePayment",
"status_code": "00",
"amount": "1.10",
"chksum": "23259ef7e03266ada789bf5a30465469",
"pInstruction": 0
}
然后怎么样:
{
"mp_request_type": "donePayment",
"status_code": "00",
"amount": "1.10",
"chksum": "23259ef7e03266ad23430465469",
"pInstruction": 0
},
{
"mp_request_type": "donePayment",
"status_code": "100",
"amount": "13.10",
"chksum": "23259ef7e03g2r32fa30465469",
"pInstruction": 0
}
如何从13.10
获取MPayTransaction.getAmount()
的第二笔金额?
答案 0 :(得分:2)
使用ArrayList<>,例如
jsonString:
[{
"mp_request_type": "donePayment",
"status_code": "00",
"amount": "1.10",
"chksum": "23259ef7e03266ad23430465469",
"pInstruction": 0
},
{
"mp_request_type": "donePayment",
"status_code": "100",
"amount": "13.10",
"chksum": "23259ef7e03g2r32fa30465469",
"pInstruction": 0
}]
将此字符串解析为ArrayList<>:
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<MPayTransaction>>(){}.getType();
Collection<MPayTransaction> collObj = gson.fromJson(jsonString, collectionType);
ArrayList<MPayTransaction> arrayList = new ArrayList<MPayTransaction>(collObj);
然后得到第二个金额的值:
arrayList.get(1).getAmount()