简体   繁体   中英

ObjectMapper adds extra Field to the JSON String

I have the following problem.

Here is my Accident class and the CommonDomainEntity class:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Accident extends CommonDomainObject {
    private String status;
    private Date accidentDate;
    private String name;
}

@Data
public abstract class CommonDomainObject {
    public Long id;

    public boolean isNew() {
        return null == getId();
    }
}

In my test class I am calling the following:

String exp = objMapper.writeValueAsString(accidents);
System.out.println(exp);
ResponseEntity<String> res = restTemplate.getForEntity("/accidents", String.class);

assertEquals(HttpStatus.OK, res.getStatusCode());
JSONAssert.assertEquals(exp, res.getBody(), false);

It throws the following error:

java.lang.AssertionError: [id=2]
Expected: new
but none found
; [id=3]
Expected: new
but none found

I already tried to out print the object exp to see whats in it, as well as I tried to print what s in accidents`.

As you see in the console logs, for some reason in the exp object there is a new=false field, and I can`t figure out where this is from.

This right here is what is in my accidents List

Accident(status=pending, accidentDate=null, name=Name), 
Accident(status=closed, accidentDate=null, name=Name)]

And this is my exp object as JSON

[{"id":2,"status":"pending","accidentDate":null,"name":"Name","new":false}, 
{"id":3,"status":"closed","accidentDate":null,"name":"Name","new":false}]

Your CommonDomainObject.isNew() method in the abstract class is evaluated as a JSON field by ObjectMapper . You must exclude it using jackson anotations.

public abstract class CommonDomainObject {
    ...
    @JsonIgnore
    public boolean isNew() {
        return null == getId();
    }
}

See:

Your MCVE would be:

  1. Call objMapper.writeValueAsString()
  2. Check why the resulting JSON string representation contains the new field

All the other code is reduntant for the reproduction of your issue :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM