From d35a1a16b9594615d369c0b02ba26b9a0869b5b8 Mon Sep 17 00:00:00 2001 From: wenshao Date: Mon, 2 Oct 2017 01:20:46 +0800 Subject: [PATCH] bug fixed for issue #1474 --- .../serializer/JavaBeanSerializer.java | 24 ++++++++- .../json/bvt/issue_1400/Issue1474.java | 51 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java diff --git a/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java b/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java index 05f74f65af..8ffac6dacb 100644 --- a/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java +++ b/src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java @@ -362,7 +362,29 @@ protected void write(JSONSerializer serializer, // } } - commaFlag = true; + boolean fieldUnwrappedNull = false; + if (fieldInfo.unwrapped + && propertyValue instanceof Map) { + Map map = ((Map) propertyValue); + if (map.size() == 0) { + fieldUnwrappedNull = true; + } else if (!serializer.isEnabled(SerializerFeature.WriteMapNullValue)){ + boolean hasNotNull = false; + for (Object value : map.values()) { + if (value != null) { + hasNotNull = true; + break; + } + } + if (!hasNotNull) { + fieldUnwrappedNull = true; + } + } + } + + if (!fieldUnwrappedNull) { + commaFlag = true; + } } this.writeAfter(serializer, object, commaFlag ? ',' : '\0'); diff --git a/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java new file mode 100644 index 0000000000..2d3f8f57d9 --- /dev/null +++ b/src/test/java/com/alibaba/json/bvt/issue_1400/Issue1474.java @@ -0,0 +1,51 @@ +package com.alibaba.json.bvt.issue_1400; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.annotation.JSONField; +import com.alibaba.fastjson.annotation.JSONType; +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + +public class Issue1474 extends TestCase { + public void test_for_issue() throws Exception { + Map extraData = new HashMap(); + extraData.put("ext_1", null); + extraData.put("ext_2", null); + + People p = new People(); + p.setId("001"); + p.setName("顾客"); + p.setExtraData(extraData); + + assertEquals("{\"id\":\"001\",\"name\":\"顾客\"}", JSON.toJSONString(p)); + } + + @JSONType(asm = false) + static class People{ + private String name; + private String id; + @JSONField(unwrapped=true) + private Object extraData; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public Object getExtraData() { + return extraData; + } + public void setExtraData(Object extraData) { + this.extraData = extraData; + } + } +}