Jackson annotation #get:JsonValue, GSON equivalent [duplicate] - java

This question already has answers here:
Using Enums while parsing JSON with GSON
(7 answers)
Closed 2 years ago.
Is there a GSON equivalent annotation for Jackson's #get:JsonValue?
I have the below enum and I need the GSON annotation as well.
enum class TransactionType(#get:JsonValue val code: Int) { ... }

It was:
enum class Type(#get:JsonValue val code: Int, val description: String) {
#SerializedName("0") NEGATIVE(2, "negative amount "),
#SerializedName("1") CREDIT(3,"Credit."),
#SerializedName("2") WAGERS(6,"wager"),
#SerializedName("3") ZERO(8, "zero.")
}
Reference:
https://javadoc.io/doc/com.google.code.gson/gson/2.8.1/com/google/gson/annotations/package-summary.html

Related

ObjectMapper returns null value on date field [duplicate]

This question already has answers here:
Jackson ObjectMapper returns null when Object variable is set to Private
(4 answers)
Closed 28 days ago.
My data is as below and saved in test folder with name risk.json
[{
"Risk": "BN",
"Classification": null,
"LastDefaultDate": "1915-04-14 00:00:00"
}]
I have RiskClass defined as below
#Data
#JsonIgnoreProperties({"document"})
public class RiskClass implements KeyedObject {
String risk;
String classification;
Date lastDefaultDate;
#Override
public String getKey() {
return risk;
}
}
In my data prepare class i am trying to populate one of the map by doing below
List<RiskClass> rList = ObjectUtils.jsonStringToObjList(readFileAsString("test", "risk.json"), RiskClass.class);
Map<String, RiskClass> riskMapLocal = new HashMap<>();
for (RiskClass rMap : rList) {
riskMapLocal.put(rMap.getRisk(), rMap);
}
now when i try to print riskMapLocal, under lastDefaultDate i get null value.
Property names in json start with uppercase - Risk, etc. Fields in POJO start with lowercase - risk, so they can't be matched automatically. You can either:
Change them in json to be lowercase
Use annotation JsonProperty on the fields to specify the name of the property to match for this field.
public class RiskClass {
#JsonProperty("Risk")
String risk;
}
Add an annotation over your property lastDefaultDate:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime lastDefaultDate;
Also change type Date to LocalDateTime as Date type is outdated (pun intended). For more details look at this question and its best answer: Spring Data JPA - ZonedDateTime format for json serialization

objectmapper only serialize specific fields [duplicate]

This question already has answers here:
How do I use a custom Serializer with Jackson?
(11 answers)
Closed 1 year ago.
I want to write a function that only serializes a POJO with given implicit field names.
For example,
class Car{
public int id;
public String type;
public Manufacture manufacture;
}
Class Manufacture{
public int id;
public String name;
}
if I want to serialize a Car object with a given list(i.e. [Car.id, Car.Manufacture.name])
Then I want to get
{
Car:{
id: xxx,
Manufacture: {
name: xxx
}
}
}
Another example, given list = [Car.type]
Then I should get
{
Car:{
type: xxx
}
}
I am currently trying to override the serializeAsField method to check if the field is in the given list, but the problem here is that I don't know the depth, then I cannot correctly compare the current field with the list.
How could I achieve it? Are there any other ways?
Mark the unwanted fields with the #JsonIgnore annotation.
On-the-fly filtering
Here is a Baeldung article that discusses using a filter to
determine which fields are serialized:
https://www.baeldung.com/jackson-serialize-field-custom-criteria
I suspect that is the answer you want.

Converting JSON Array to Java Array always throws empty values

So I have this variable specCifDetailsReturn which contains the ff. payload
[
{"ax21:cHType":"S",
"ax21:cardNumber":4***********7126,"ax21:returnCde":"00",
"ax21:cancelCode":"",
"ax21:vipCode":"",
"ax21:custrNbr":"0*****3426"},
{"ax21:cHType":"S",
"ax21:cardNumber":4***********3038,"ax21:returnCde":"00",
"ax21:cancelCode":"H",
"ax21:vipCode":"",
"ax21:custrNbr":"0*****3426"}
]
And the ff. Model Class to extract the params I need from the Array
#Data
#AllArgsConstructor
#NoArgsConstructor
#JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)
public final class SpecCifInfo {
#JsonAlias("ax21:cHType")
private String cHType;
#JsonAlias("ax21:cardNumber")
private String cardNumber;
}
I am trying to convert it to a Java ArrayList so that I could loop into it and find a card number. But for some reason it always throws a null value on the log even though the specCifDetailsReturn variable has a value. Below is the snippet of my code.
Gson gson = new Gson();
Type type = new TypeToken<List<SpecCifInfo>>(){}.getType();
ArrayList<SpecCifInfo> specDetails = gson.fromJson(specCifDetailsReturn.toString(),type);
for (SpecCifInfo specInfo : specDetails){
LOGGER.debug("Spec CIF Details", specInfo.getCHType() + "-" + specInfo.getCardNumber());
}
Sample Output of the SpecCifInfo Object that has null values
Those annotations are for the Jackson library, and you are manually using Gson. You should either keep them and just let Spring handle the deserialization for you by specifying a List<SpecCifInfo> parameter in the controller method, or you should use GSON's #SerializedName annotation. Either way will work.

Java Jackson annotation for changing field [duplicate]

This question already has answers here:
How to convert a JSON string to a Map<String, String> with Jackson JSON
(11 answers)
Closed 4 years ago.
I have to call 3rd party API for currency exchange rate, but the JSON returned keep changing, if i request a MYR to USD conversion, it will return me: {"MYR_USD":0.246731}, so if i request for KRW to USD, it will return me {"KRW_USD":0.000888}.
I will have to map the returned result into pojo using #JsonProperty, is there any ways that works?
My current hard-coded workaround:
#JsonIgnoreProperties(ignoreUnknown = true)
public class FreeCurrencyExchangeRate {
#JsonProperty("MYR_USD")
private double rate;
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
}
{"A":5} is an object with field A having value 5.
No {"A":5} is a Map with key/value pair A=5.
Both can be true, but since the value before : is dynamic (changing), it the second interpretation you need.
So don't ask for JSON to be converted to a POJO (FreeCurrencyExchangeRate).
Ask for it to be converted to a Map, then iterate that map.

How to parse symbols as JSON keys in Java with Gson? [duplicate]

This question already has answers here:
How can I convert JSON to a HashMap using Gson?
(16 answers)
Converting deeply nested json to java object and vice versa
(3 answers)
Closed 4 years ago.
I want to get some ideas to handle a JSON structure like this.
Especially for the '/' key.
{
"tree":{
"/":"1234567890"
},
"parents":null
}
I created this (works if I replace / with slash in the given JSON)
private class Test {
private SubDirectory tree;
private String parents;
}
private class SubDirectory {
private String slash;
// private String /; obviously not working :D
}
using Gson with a InputStreamReader and then:
Test p = gson.fromJson(reader, Test.class);
So my first idea is to check reader and replace that / to slash.
But really ?! ...

Categories

Resources