如何在Java中删除JSON多余的行?

时间:2018-12-19 05:01:00

标签: java json

我正在尝试将json发布到服务器。但是json出了点问题。 JSON包含“ id”和“ record_id”,但我没有设置2值。如何从json中删除它?

final Record rec = new Record();

rec.setAccountbook(bookCid);
rec.setUser(pref.getString(Constants.USER_ID, ""));
rec.setCreatedAt(currentDateandTime);
rec.setRecordType(Integer.toString(valtype));
rec.setRemark(strremark);
rec.setAmount(Double.toString(dbamount));
rec.setAsset(strasset);
rec.setCategory(type);

//I didn't set this 2, but this 2 show in the json
//rec.setId(1);
//rec.setRecord_id(1); 

String json = new Gson().toJson(rec);
Log.d("JSON_MSG",""+json);

结果

D/JSON_MSG:
{  
    "accountbook":"04e19a16-ea72-43da-b2b8-fe388ec56fd4",
    "amount":"522.0",
    "asset":"Cash",
    "category":"吃喝",
    "createdAt":"2018-12-19",
    "id":0,
    "recordType":"1",
    "record_id":0,
    "remark":"",
    "user":"43"
}

Java:记录类

private int id;
private int record_id;
private String cid, amount, accountbook, asset, createdAt, recordType, remark, category, user;
private String record_cid, record_amount, record_category, record_book, record_type, record_remark, record_createdAt, record_asset, record_user;

//Declare Constructor
public Record(String amount, String accountbook, String asset, String createdAt, String recordType, String remark, String category, String user) {
    this.amount = amount;
    this.accountbook = accountbook;
    this.asset = asset;
    this.createdAt = createdAt;
    this.recordType = recordType;
    this.remark = remark;
    this.category = category;
    this.user = user;
}

//All the setter & getter

2 个答案:

答案 0 :(得分:1)

在id字段上使用transient关键字。java中的修饰符transient可以应用于类的字段成员,以关闭这些字段成员上的序列化。标记为瞬态的每个字段都不会序列化。

this链接中查看瞬态现象

例如,

private transient int id;
private int record_id;
private String cid, amount, accountbook, asset, createdAt, recordType, remark, category, user;
private String record_cid, record_amount, record_category, record_book, record_type, record_remark, record_createdAt, record_asset, record_user;

//Declare Constructor
public Record(String amount, String accountbook, String asset, String createdAt, String recordType, String remark, String category, String user) {
    this.amount = amount;
    this.accountbook = accountbook;
    this.asset = asset;
    this.createdAt = createdAt;
    this.recordType = recordType;
    this.remark = remark;
    this.category = category;
    this.user = user;
}

答案 1 :(得分:0)

需要在字段上添加@JsonIgnore批注 @JsonIgnore private int id;