Gson序列化从Hashmap中排除键

时间:2014-09-17 15:55:25

标签: json serialization gson

我的课是这个

public class GiftCard {
    Map<String, Object> extendedProperties;
    String expiryDate;
    double originalAmount;
    String cardNumber;
}

hashmap有许多值,包括&lt;“pin”:1234&gt;

当我执行log(gson.json(giftCard))时,它也会打印引脚。

如何防止引脚被记录(在extendedProperties中记录其他值时)?

1 个答案:

答案 0 :(得分:0)

您不想更改原始引脚值,您需要它吗?那你应该使用toString方法。修改您的GiftCard课程。请参阅下面的代码及其中的注释。实际上有更多的评论而不是代码:

public class GiftCard implements Cloneable {
    Map<String, Object> extendedProperties;
    String expiryDate;
    double originalAmount;
    String cardNumber;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        GiftCard cloned = (GiftCard)super.clone();
        // the default behavior of clone() is to return a shallow copy of the object. 
        // This means that the values of all of the original object’s fields are copied to the fields of the new object.
        // If the fields are primitive types, the changes made to this object will not be reflected to cloned ones.
        // But if the fields are not primitive, only their references are cloned, 
        // which means any change on that fields, are applied to original and the cloned objects.
        // So here we have to get a copy of your hash map.
        cloned.extendedProperties = new HashMap<String, Object>(this.extendedProperties);
        return cloned;
    }

    @Override
    public String toString() {
        try {
            GiftCard giftCardToPrint = null;

            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();

            if(this.extendedProperties != null && this.extendedProperties.get("pin") != null) {
                // You don't want to change the original pin value so clone original instance, see clone method.
                giftCardToPrint = (GiftCard) this.clone();  
                giftCardToPrint.extendedProperties.put("pin", "*");
            } else {
                giftCardToPrint = this;
            }

            return gson.toJson(giftCardToPrint);
        } catch (Exception e) {
            e.printStackTrace();
            return super.toString();
        }

    }
}

尝试以下代码:

System.out.println("giftCard toString:" + giftCard.toString());
System.out.println("giftCard toJson  :" + gson.toJson(giftCard));
System.out.println("giftCard.pin     :" + giftCard.extendedProperties.get("pin"));

输出:

giftCard toString:{"cardNumber":"1111 2222 3333 4444","extendedProperties":{"pin":"*"},"originalAmount":0.0}
giftCard toJson  :{"cardNumber":"1111 2222 3333 4444","extendedProperties":{"pin":"1234"},"originalAmount":0.0}
giftCard.pin     :1234