alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.72k stars 6.5k forks source link

使用JSONPath.set对未知属性赋值失败 #4312

Open quicklyfast opened 1 year ago

quicklyfast commented 1 year ago

在以下的测试用例中,期望使用JSONPath.set(p, "$.age", 13)修改属性age的值为13,但读到age值仍然为12

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.alibaba.fastjson.annotation.JSONField;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

public class MapperTest {
  static class People {
    private String name;
    private Map<String, Object> extra = new HashMap<>();

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public Map<String, Object> getExtra() {
      return extra;
    }

    public void setExtra(Map<String, Object> extra) {
      this.extra = extra;
    }

    @JSONField(unwrapped = true)
    public void set(String key, Object value) {
      this.extra.put(key, value);
    }

    @JSONField(unwrapped = true)
    public Object get(String key) {
      return this.extra.get(key);
    }
  }

  @Test
  public void test() {
    String json = "{\"name\": \"lisi\", \"age\": 12}";
    People p = JSON.parseObject(json, People.class);

    Assertions.assertEquals("lisi", p.name); // 成功
    Assertions.assertEquals(12, p.extra.get("age")); // 成功, 使用JSON.parseObject对未知属性赋值成功

    JSONPath.set(p, "$.age", 13);
    Assertions.assertEquals(13, p.extra.get("age")); // 失败: 使用JSONPath.set对未知属性赋值失败, p.extra.get("age") == 12
  }
}
wenshao commented 1 year ago

https://github.com/alibaba/fastjson2/releases/tag/2.0.19 请用新版本