类A声明了多个JSON字段 [英] class A declares multiple JSON fields

查看:113
本文介绍了类A声明了多个JSON字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个A类,它有一些私有字段,同一个类继承另一个B类,它也有一些私有字段在A类中。

  public class A extends B {
private BigDecimal netAmountTcy;
私人BigDecimal netAmountPcy;
private BigDecimal priceTo;
私有String段;

私人BigDecimal taxAmountTcy;
private BigDecimal taxAmountPcy;
私人BigDecimal tradeFeesTcy;
私人BigDecimal tradeFeesPcy;

//上述字段的getter和setter

$ b

和B类已经有一些私人fiedls在A类中



现在当我尝试从类A创建JSON字符串时,我得到以下异常:

  class com.hexgen.ro.request.A声明多个名为netAmountPcy的JSON字段

如何解决这个问题?



因为它们是私有字段,所以不应该有任何在创建json字符串时出现问题,但我不确定。



我创建json字符串,如下所示:

  Gson gson = new Gson(); 
tempJSON = gson.toJson(obj);

这里obj是类A的对象

解决方案

不要认为这种说法是真实的,GSON在序列化时查找对象的私有字段,这意味着包含所有超类的私有字段,并且当您具有相同名称的字段时,它会引发错误。



如果您不想包含任何特定字段,则必须使用 transient 关键字标记它,例如:

 私人瞬态BigDecimal tradeFeesPcy; 


i have a class A which has some private fields and the same class extends another class B which also has some private fields which are in class A.

public class A extends B {
    private BigDecimal netAmountTcy;
    private BigDecimal netAmountPcy;   
    private BigDecimal priceTo;  
    private String segment;

    private BigDecimal taxAmountTcy;
    private BigDecimal taxAmountPcy;   
    private BigDecimal tradeFeesTcy;
    private BigDecimal tradeFeesPcy;

// getter and setter for the above fields

}

and class B has got some private fiedls which are in class A

now when i try to create JSON string from above class A i get the following exception :

class com.hexgen.ro.request.A declares multiple JSON fields named netAmountPcy

How to fix this?

Since they are private fields there should not be any problem while creating json string i guess but i am not sure.

i create json string like the following :

Gson gson = new Gson();
 tempJSON = gson.toJson(obj);

here obj is the object of class A

解决方案

Since they are private fields there should not be any problem while creating json string

I don't think this statement is true, GSON looks up at the object's private fields when serializing, meaning all private fields of superclass are included, and when you have fields with same name it throws an error.

If there's any particular field you don't want to include you have to mark it with transient keyword, eg:

private transient BigDecimal tradeFeesPcy;

这篇关于类A声明了多个JSON字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆