Skip to content

JsonWrapper参数中的字段必须要在json字符串中出现 #104

@junlincao

Description

@junlincao
  static class AAA {
        @JsonProperty("name_1")
        private String name;

        @JsonIgnore
        private String partA;
        @JsonIgnore
        private String partB;

        @JsonWrapper
        public void foreignFromJson(@JsonProperty(value = "parts", from ={"p2"}, required = false) String parts) {
            if(parts == null){
                return;
            }
            String[] ps = parts.split(",");
            partA = ps[0];
            partB = ps.length > 1 ? ps[1] : null;
        }
    }
String jsonStr = "{'name':'aaa', 'name_1':'bbb', 'parts':'1,2'}".replace('\'', '\"');
AAA aaa = JsonIterator.deserialize(jsonStr, AAA.class);

上面这段代码可行

String jsonStr = "{'name':'aaa', 'name_1':'bbb'}".replace('\'', '\"');
AAA aaa = JsonIterator.deserialize(jsonStr, AAA.class);

但是当json中不包含“parts”字段后,解析就会报错:
argument 1 should have type java.lang.String, got com.jsoniter.ReflectionObjectDecoder$1

还有其它细节吐槽,在这里一并提出来:

  1. JsonProperty 直接设置value值无效,必须要设置from={},to={},如果没有设置from和to,value应该就作为from和to的默认值,这样比较方便
  2. JsonProperty 作用在属性字段上和方法上效果不一致,在作用于JsonWrapper方法字段上的时候,from和to设置的值会被value值覆盖... 参考第一条,感觉有点混乱
  3. 默认情况下,JsonIgnore 和 JsonProperty同时修饰属性的时候,JsonIgnore 无效。这条可以无视...
  4. 对属性字段设置@JsonIgnore,但是设置了getter和setter,则这个属性上的设置都是无效的。。。
    例如: static class AAA {
    private String test;
    @JsonIgnore
    private String name;
    public void setName(String name) {
    this.name = name;
    }
    }
    String jsonStr = "{'name':'aaa', 'test':'bbb'}".replace(''', '"');
    AAA aaa = JsonIterator.deserialize(jsonStr, AAA.class);
    仍然会将name值设置进去。必须要对getter和setter设置@JsonIgnore,或者参GsonCompatibilityMode停掉所有方法的binding

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions