I have this JSON snippet. My problem is the key under transactions{} in this example it is set to "Request ID 000002" However this is part of a response to an API request and that value will change. It will always be what is between the [] in the "found detail" property, but I won't know what it is until I POST the request and receive the response.
"response_state" : {
"filter_records_removed" : 0,
"filter_records_reviewed" : 1,
"filter_redaction" : false,
"found" : 1,
"found_detail" : "Found Records [Request ID 000002] available the time of query",
"missing" : 0,
"results" : true,
"transactions" : {
"Request ID 000002" : {
"complete" : false,
"confirmed" : false,
"event_transaction_id" : "Request ID 000002",
"event_type" : "software_update",
"expiration_mark" : false,
"expiry" : 1727559823240
}
}
This is the Java Class. I can't really define the value of the @SerializedName ahead of time like it is here in the example.
public class EFDTransactions {
@SerializedName("Request ID 000002")
@Expose private EFDTransaction transaction;
public EFDTransactions() {
// TODO Auto-generated constructor stub
}
public EFDTransaction getTransaction() {
return transaction;
}
public void setTransaction(EFDTransaction transaction) {
this.transaction = transaction;
}
I am trying to create the class structure so that I can do something like this, where I have already created a JsonObject from the JSON string that was returned from the API request:
Gson rspgson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.create();//new Gson();
//responsejobj is the JsonObject created from the JSON string that is the response
EFDTransactions trans = rspgson.fromJson(responsejobj,EFDTransactions.class);
Do I need to write a custom deserializer? I found this thread on using Reflection to modify the @SerializedName annotation value. I have not tried it yet. Is there another approach?
Modify a class definition's annotation string parameter at runtime
I found this thread, but this isn't Java: Set Dynamic SerializedName annotation for Gson data class
I found this thread and tried creating a Map, that did not work. The map was null after the fromJson(). It works using the above class with the test known value for @SerializedName: Set Dynamic SerializedName annotation in android java
Here is the same class I created with a Map
public class EFDTransactions {
@Expose public Map<String, EFDTransaction> transaction;
public EFDTransactions() {
// TODO Auto-generated constructor stub
}
public Map<String, EFDTransaction> getTransaction() {
return transaction;
}
transactions, with ans. It should work with the map.