user3358472
user3358472

Reputation: 43

.net json property conversion in java - @JsonProperty

Need some help here! I have a Java Rest API which is getting data from a .net endpoint and passing it on to the UI. The JSON properties are in capital case and I want to convert them in JAVA before sending it to the UI. Any pointers on this?

In java, I have a class like below:

public class Person {
@JsonProperty("Name")
private String name;
@JsonProperty("Age")
private int age;
}

I am using @JsonProperty as keys in .net are starting with capitalCase. How can I convert this back before sending it to the UI in Java?

Thanks for the help!

Upvotes: 0

Views: 168

Answers (1)

mentallurg
mentallurg

Reputation: 5207

Create another class with the same structure and use there other names that you want. Something like this:

// Class to read .NET object
public class Person {
    @JsonProperty("Name")
    private String name;
    @JsonProperty("Age")
    private int age;
}

// Class to represent the object in Java REST API
public class Person {
    @JsonProperty("name")
    private String name;
    @JsonProperty("age")
    private int age;
}


// Class to represent the object in Java REST API,
// in case you use some standard library that
// uses property names for JSON as is
public class Person {
    private String name;
    private int age;
}

Of course you should put these classes into different packages.

Your code can look as follows:


xxx.dotnet.Person dotnetPerson = doSomethingViaDotNet(...);
yyy.rest.Person restPerson = new yyy.rest.Person();
restPerson.setName(dotnetPerson.getName());
restPerson.setAge(dotnetPerson.getAge());
...
return restPerson;

If you decide to use MapStruct, your code may looks as follows:

@Mapper
public interface PersonMapper {
    PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    yyy.rest.Person dotnetToRest(xxx.dotnet.Person dotnetPerson);
}

Since all attributes have the same names and types you don't need anything else in your mapper.

MapStruct will generate a class that implements this interface. Usage will be as follows:

restPerson = PersonMapper.INSTANCE.dotnetToRest(dotnetPerson);

Upvotes: 1

Related Questions