I want to be able to have different names for serialized and deserialized json objects when using jackson in java.
To be a bit more concrete: I am getting data from an API that is using one name standard on their JSON attributes, but my endpoints use a different one, and as I in this case just want to pass the data along I would like to be able to translate the attributes to my name standard.
I have read similar questions on here, but I simply can't seem to get it working.
private String defaultReference;
#JsonProperty(value = "default_reference", access = JsonProperty.Access.WRITE_ONLY)
public void setDefaultReference(String defaultReference)
{
this.defaultReference = defaultReference;
}
#JsonProperty(value = "defaultReference", access = JsonProperty.Access.READ_ONLY)
public String getDefaultReference()
{
return defaultReference;
}
That is my latest attempt. problem with this is that it always returns null, so the setter is not used.
I have also tried:
#JsonProperty(value = "default_reference", access = JsonProperty.Access.WRITE_ONLY)
private String defaultReference;
#JsonProperty(value = "defaultReference", access = JsonProperty.Access.READ_ONLY)
public String getDefaultReference()
{
return defaultReference;
}
This sort of works. It can deserialize default_reference. Problem is that in my JSON response I get both default_reference and defaultReference. Preferably I would only get defaultReference.
Has anyone done anything similar and see what is wrong with what I've tried?
You're on the right track. Here's an example of this working with a test JSON document.
public static class MyClass {
private String defaultReference;
#JsonProperty(value = "default_reference")
public void setDefaultReference(String defaultReference) {
this.defaultReference = defaultReference;
}
#JsonProperty(value = "defaultReference")
public String getDefaultReference() {
return defaultReference;
}
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
MyClass instance = objectMapper.readValue("{\"default_reference\": \"value\"}", MyClass.class);
objectMapper.writeValue(System.out, instance);
// Output: {"defaultReference":"value"}
}
}
Another Alternative is
#JsonSetter("default_reference")
public void setDefaultReference(String defaultReference) {
this.defaultReference = defaultReference;
}
#JsonGetter("defaultReference")
public String getDefaultReference() {
return defaultReference;
}
Related
I'm trying to fetch JSON data from my website throw REST API with retrofit2.
But when I run the app this error message show:
Can not find a (Map) Key deserializer for type [simple type, class com.example.app.ReferralApiModel]
I'm using retrofit library.
This is my code for the retrofit call:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.URL)
.addConverterFactory(JacksonConverterFactory.create())
.client(defaultHttpClient)
.build();
ReferralsPlaceHolderApi placeHolderApi = retrofit.create(ReferralsPlaceHolderApi.class);
Call<List<Map<ReferralApiModel, String>>> call = placeHolderApi.getReferrals();
And this is my ReferralsPlaceHolderApi class:
public interface ReferralsPlaceHolderApi {
#JsonDeserialize(keyAs = ReferralsCustomDeserializer.class)
#GET(AppConfig.ENDPOINT_REFERRALS)
Call<List<Map<ReferralApiModel, String>>> getReferrals();
}
Also this is my ReferralApiModel class:
public class ReferralApiModel {
private String date;
private String amount;
private String currency;
private String status;
public ReferralApiModel() {}
public ReferralApiModel(String date, String amount, String currency, String status) {
this.date = date;
this.amount = amount;
this.currency = currency;
this.status = status;
}
public String getDate() {
return date;
}
public String getAmount() {
return amount;
}
public String getCurrency() {
return currency;
}
public String getStatus() {
return status;
}
}
This is the json data that I'm trying to get:
"[{\"id\":\"1\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"1\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"302\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 12:53:29\",\"status\":\"0\",\"payment\":\"0\",\"username\":\"aaa\"},{\"id\":\"2\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"2\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"303\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 13:03:43\",\"status\":\"1\",\"payment\":\"0\",\"username\":\"aaa\"},{\"id\":\"3\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"2\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"304\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 13:04:33\",\"status\":\"2\",\"payment\":\"0\",\"username\":\"aaa\"}]"
Can anyone help me with this?.
Also I've found that this problem may be a class mapping problem, from this answer :
https://stackoverflow.com/a/16383752/8055951
If it's ?!, Can someone tell me how to map the ReferralsPlaceHolderApi class.
Thanks.
Jackson cannot deserialize custom classes as map keys. The key of your deserialized map is ReferralApiModel. I order to achieve it, you need to write your own KeyDeserializer and register it for your class with Jackson. You can see here or here how to do that.
Also the json string in the question makes it look as if you don't need to deserialize into List<Map<ReferralApiModel, String>>, but into List<ReferralApiModel> instead. Which would make writing custom key deseriaslizers redundant.
Edit: Ok, receiving json array, which has been json sting-ified is just strange. It would be best, if someone on your team is responsible for this API and can fix it. If not, you have workarounds:
Parse twice with object mapper - first parse it to normal string, which would be json array, then parse this string into List<YourObject>
ObjectMapper mapper = new ObjectMapper();
String string = mapper.readValue(initialJson, String.class);
List<ReferralApiModel> list = mapper.readValue(string, TypeFactory.defaultInstance().constructCollectionType(List.class, ReferralApiModel.class));
list.forEach(System.out::println);
Turn it manually into proper json array. That means remove first and last char - double quote, and remove all those escapes - \. Something like this:
String jsonString = "the string";
jsonString = jsonString.substring(1, jsonString.length() - 1).replace("\\", "");
ObjectMapper mapper = new ObjectMapper();
List<ReferralApiModel> list = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, ReferralApiModel.class));
list.forEach(System.out::println);
I have two classes Athlete and Injury, the last one contains Athlete object, when the serialization happens I get the following JSON representation back:
{"id":X,"kindOfInjury":"...","muscle":"...","side":"...","outOfTrainig":Y,"injuryDate":"2018-Jun-02","athlete":{"id":X,"firstName":"...","lastName":"...","age":X,"email":"..."}}
I don't want to get all the information about Athlete - just an id value, like "athleteId":1, instead of getting the entire object representation.
So, I have found that I need to apply my custom Serializer which implements StdSerializer on Injury class. So this is what I got so far:
class InjurySerializer extends StdSerializer<Injury> {
public InjurySerializer() {
this(null);
}
public InjurySerializer(Class<Injury> i) {
super(i);
}
#Override
public void serialize(
Injury value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.getId());
jgen.writeStringField("kindOfInjury", value.getKindOfInjury());
jgen.writeStringField("muscle", value.getMuscle());
jgen.writeStringField("side", value.getSide());
jgen.writeNumberField("outOfTraining", value.getOutOfTraining());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
jgen.writeStringField("injuryDate", ourformat);
jgen.writeNumberField("athleteId", value.getAthlete().getId());
jgen.writeEndObject();
}
}
And the actual Injury class:
#Entity
#Table(name = "INJURY")
#JsonSerialize(using = InjurySerializer.class)
public class Injury {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "INJURY_ID")
private Long id;
#Column(name = "KIND_OF_INJURY")
private String kindOfInjury;
#Column(name = "MUSCLE")
private String muscle;
#Column(name = "SIDE")
private String side;
#Column(name = "OUT_OF_TRAINING")
private Integer outOfTraining;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MMM-dd")
#Column(name = "INJURY_DATE")
private Date injuryDate;
#ManyToOne
#JoinColumn(name = "ATHLETE_ID")
private Athlete athlete;
So, this solution works, but it looks terrible...
Question is the following:
1) Is there any mechanism which provides me functionality to change the serialization of only ONE property which I really need, instead of writing all this tedious code, where the actual change is only in this line? :
jgen.writeNumberField("athleteId", value.getAthlete().getId());
2) Could you recommend me something to read about Jackson because at this point I have a little bit mess in my head about it?
Thanks for the patience and I'm looking forwards for your responses :)
You can use the Data Transfer Object (DTO) for that purposes.
Create a simple POJO like this:
public class InjuryDTO {
//all other required fields from Injury model...
#JsonProperty("athlete_id")
private Long athleteId;
}
And converter for it:
#Component
public class InjuryToDTOConverter{
public InjuryDTO convert(Injury source){
InjuryDTO target = new InjuryDTO();
BeanUtils.copyProperties(source, target); //it will copy fields with the same names
target.setAthleteId(source.getAthlete().getId());
return target;
}
}
You can use it like that:
#RestController("/injuries")
public class InjuryController {
#Autowired
private InjuryToDTOConverter converter;
#Autowired
private InjuryService injuryService;
#GetMapping
public InjuryDTO getInjury(){
Injury injury = injuryService.getInjury();
return converter.convert(injury);
}
}
The benefit of this approach is that you can have multiple DTOs for different purposes.
You might find it less tedious to use the #JsonIgnore annotation instead of writing a custom serializer. Take this example
public class Person {
private int id;
#JsonIgnore
private String first;
#JsonIgnore
private String last;
#JsonIgnore
private int age;
// getters and setters omitted
}
When Jackson serializes this class, it only includes the "id" property in the resulting JSON.
#Test
void serialize_only_includes_id() throws JsonProcessingException {
final var person = new Person();
person.setId(1);
person.setFirst("John");
person.setLast("Smith");
person.setAge(22);
final var mapper = new ObjectMapper();
final var json = mapper.writeValueAsString(person);
assertEquals("{\"id\":1}", json);
}
You can try manupulating json string using basic string replace method.
I ran your json and converted it to your desired format:
public static void main(String args[]) {
String json = "{\"id\":123,\"kindOfInjury\":\"...\",\"muscle\":\"...\",\"side\":\"...\",\"outOfTrainig\":Y,\"injuryDate\":\"2018-Jun-02\",\"athlete\":{\"id\":456,\"firstName\":\"...\",\"lastName\":\"...\",\"age\":14,\"email\":\"...\"}}";
JsonObject injury = new JsonParser().parse(json).getAsJsonObject();
JsonObject athelete = new JsonParser().parse(injury.get("athlete").toString()).getAsJsonObject();
String updateJson = injury.toString().replace(injury.get("athlete").toString(), athelete.get("id").toString());
updateJson = updateJson.replace("athlete", "athleteId");
System.out.println(updateJson);
}
output:
{"id":123,"kindOfInjury":"...","muscle":"...","side":"...","outOfTrainig":"Y","injuryDate":"2018-Jun-02","athleteId":456}
Dependency:
implementation 'com.google.code.gson:gson:2.8.5'
If you can replace with regex that will be bit more cleaner.
I have an objects class A:
public class A {
private Long id;
private String name;
private String mail;
private String moreData;
// ...
}
class B:
public class B {
private Long id;
private String name;
private String crc;
// ...
}
Can I use jackson to provide field mapping from object A to B copying correspond fields into target object.
I need from object
A {
Long id = 23L;
String name = "name";
String mail = "mail";
String moreData = "moreData";
// ...
}
get as target object
B {
Long id = 23L;
String name = "name";
String crc = mull;
// ...
}
after object mapping processing...
Is it possible implement solution using com.fasterxml.jackson in simple way?
Sure you can. Not withstanding a full understanding of why you want to do this, or that I think there might be more efficient ways than converting to JSON then back, but if you would like to use Jackson, here is what I would do:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
B b = objectMapper.readValue(objectMapper.writeValueAsString(a), B.class);
Hope this helps. should do the job. The key will be to tell Jackson to not fail on unknown properties so it drops those you are not sure of.
I have a class called Lookup that has two properties:
public class Lookup {
private String surveyName;
private String GUID;
public Lookup(String name, String guid){
this.surveyName = name;
this.GUID = guid;
}
}
In another class, I have a list of Lookup that I am trying to serialize and save to file. This is how I'm doing it:
List<Lookup> lookup = new ArrayList<Lookup>();
lookup.add(new Lookup("foo","bar"));
XStream serializer = new XStream();
serializer.alias("Lookups",List.class);
String xml = serializer.toXML(lookup);
The XML I end up with is:
<Lookups>
<Lookup>
<GUID>bar</GUID>
</Lookup>
</Lookups>
As you can see, it only serialized the field GUID but not the field surveyName. Why is it ignoring that field?
Are you sure that you don't modify Lookup variable somewhere else. This code runs fine
public class Test {
public static void main(String[] args) {
List<Lookup> lookup = new ArrayList<Lookup>();
lookup.add(new Lookup("foo","bar"));
XStream serializer = new XStream();
serializer.alias("Lookups",List.class);
String xml = serializer.toXML(lookup);
System.out.println(xml);
}
}
class Lookup {
private String surveyName;
private String GUID;
public Lookup(String name, String guid){
this.surveyName = name;
this.GUID = guid;
}
}
Output:
<Lookups>
<Lookup>
<surveyName>foo</surveyName>
<GUID>bar</GUID>
</Lookup>
</Lookups>
Silly me, the mistake was completely on my end. The field name was receiving an empty string, and thus XStream must have been ignoring it.
I have the following POJO class for a JSON object:
public class JSONChangeSet {
public JSONChangeSet {
System.out.println("Owner: " + owner);
}
#SerializedName("comment")
private String comment;
#SerializedName("lastUpdatedDate")
private String modifiedDate;
#SerializedName("owner")
private Resource owner;
#SerializedName("modifiedBy")
private Resource modifier;
public String getComment() {
return comment;
}
}
Obviously this doesnt work, because the field owner has not yet a value assigned when the constructor is called. Is there any possibility to call a method automatically after the JSON object is parsed?
You tagged your question with gson, but I would recommend you the Jackson library instead, because I saw your last two questions, and seems like gson is not flexible enough for you.
In Jackson your example would look like this:
public final class JSONChangeSet {
private final String comment;
private final Resource owner;
#JsonCreator
public JSONChangeSet(
#JsonProperty("comment") final Resource owner,
#JsonProperty("comment") final String comment
) {
this.comment = comment;
this.owner = owner;
}
public String getComment() {
return comment;
}
}
With this solution you can have immutable objects, which will built by the constructor. It's also good for the DI pattern. And BTW Jackson is lightning fast.
You may want to read this question also.
I think Gson does not has a "listener" for that. You can try the following trick:
static class JSONChangeSet {
#SerializedName("comment")
private String comment;
#SerializedName("owner")
private int owner;
}
static class JSONChangeSetDeserializer implements JsonDeserializer<JSONChangeSet> {
Gson gson = new Gson();
#Override
public JSONChangeSet deserialize(final JsonElement json, final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException {
final JSONChangeSet obj = gson.fromJson(json, typeOfT);
// Code you want to run
System.out.println("Owner: " + obj.owner);
return obj;
}
}
public static void main(final String[] args) throws Exception, JsonMappingException, IOException {
final GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(JSONChangeSet.class, new JSONChangeSetDeserializer());
gson.create().fromJson("{\"comment\": \"it works!\", \"owner\": 23}", JSONChangeSet.class);
}