My situation is as follows: Object TableC
has 4 fields. Only 3 fields (field_C1
, field_C2
, and field_C3
) are read from the JSON string. The fourth field field_C4
is defined within the object with a default value.
When I serialize the object instance (for output) - it ignores the field field_C4
, I was expecting the default value of "1"
or "null"
. When I explicitly define a value to the instance-field within the program to "NEW"
, it does include it in the Json output string.
Looking at the output, it looks as if the constructor is also ignored when the object instance is created during deserialization.
What would be the best practice to activate the other fields for the object instance - which are not included in the Deserialized version of the input Json String?
package newpackage;
import java.util.List;
import com.google.gson.*;
public class jsonwithconstructor {
public static void main(String[] args) throws ClassNotFoundException {
String jsonstring = "{'TableC':["
+ "{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
+ "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'}"
+ "]}";
jsonstring = jsonstring.replace('\'', '"');
System.out.println(jsonstring);
RootObject root = new GsonBuilder().create().fromJson(jsonstring, RootObject.class);
for (int i=0; i < root.TableC.size(); i++){
System.out.println(root.TableC.get(i));
}
System.out.println();
//root.TableC.get(0).field_C4 = "NEW";
for (int i=0; i < root.TableC.size(); i++){
System.out.println(root.TableC.get(i));
}
System.out.println();
Gson gson = new Gson();
String jsonoutput = gson.toJson(root);
System.out.println(jsonoutput);
}
public class TableC{
public String field_C1;
public String field_C2;
public String field_C3;
public String field_C4 = "1";
public TableC(){
this.field_C4 = "1";
}
@Override
public String toString() {
return ("TableC" + ", " + this.field_C1 + ", " + this.field_C2 + ", " + this.field_C3 + ", " + this.field_C4);
}
}
public class RootObject{
public List<TableC> TableC;
}
}
The output is shown below:
{"TableC":[{"field_C1":"C_11","field_C2":"C_12","field_C3":"C_13"},{"field_C1":"C_21","field_C2":"C_22","field_C3":"C_23"}]}
TableC, C_11, C_12, C_13, null
TableC, C_21, C_22, C_23, null
TableC, C_11, C_12, C_13, NEW
TableC, C_21, C_22, C_23, null
{"TableC":[{"field_C1":"C_11","field_C2":"C_12","field_C3":"C_13","field_C4":"NEW"},{"field_C1":"C_21","field_C2":"C_22","field_C3":"C_23"}]}