'Java JSON writes double

I'm trying to deserialize a java object to JSON object with the code below and I recognized that the parameters which start with upper case has been written double. For example;

Request req = new Request();
req.setMAC("abcdef");
req.setMACParams("term:id:orderno");
req.setOrderNo("999xdef123");

final ObjectMapper mapper = new ObjectMapper(); 

String json = mapper.writeValueAsString(req);

Inside of json string:

{ "MAC":"abcdef","MACParams":"term:id:orderno","OrderNo":"999xdef123","mac":"abcdef","macparams":"term:id:orderno","orderno":"999xdef123" }

So what should i do to prevent this double code?



Solution 1:[1]

This problem occurs due to upper case letters used in field property names. Just use @JsonProperty annotation in each field of Request class then it will de-serialize to given name only.

E.g.:

class Request{
    @JsonProperty("MAC")
    private String mac;

}

Solution 2:[2]

Do you have getter & setter in your class Request, but those getter does not follow java bean rules, The field "MAC" whith getMAC and setMAC whill be correct , but "getMac" will generate mac twice in the result.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 xiaoming