I am stuck in this issue, Jackson is able to deserialize the object correctly but Gson is printing empty objects. Has anyone faced this issue before. I am dependent on a library that uses gson and it wasn't working so I am trying to reproduce it like below. If gson needs any custom deserializer, then I may need to update the dependent library.
File file = new File("src/test/resources/rups.json");
Reader reader = new InputStreamReader(new FileInputStream(file));
Gson gson = new Gson();
PaymentRequest paymentRequest = gson.fromJson(reader, PaymentRequest.class);
System.out.println(gson.toJson(paymentRequest));
//prints empty object within paymentRequest
ObjectMapper objectMapper = new ObjectMapper();
paymentRequest = objectMapper.readValue(file, PaymentRequest.class);
System.out.println(paymentRequest.getData());
//prints fine
}
Edit - Gson version is 2.8.6
CodePudding user response:
Can you try this?
Gson gson = new GsonBuilder().create();
PaymentRequest paymentRequest = gson.fromJson(reader, PaymentRequest.class);
CodePudding user response:
This was due to underscore naming convention in the JSON object. Gson was not able to deserialize underscore fields like for example "is_this_awesome": "yes yes", once it was given instructions to do so, it helped
All I had to do was below. Now the next challenge is how to make it available to the external library I am using.
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
