转换时Gson忽略了我的字段

我创建了一个模型:

public class UserRequest extends DefaultRequest { public String username; public String password; public String id; public UserRequest(String username, String password) { this.username = username; this.password = password; } } 

我称之为:

 //code truncated UserRequest userRequest = new UserRequest(username,password); response = getRestClient().sysInitApp(userRequest).execute(); //code truncated 

然后我打印出请求正文,而不是:

 { "username":"farid", "password":"passfarid", "id":null } 

我明白了:

 { "username":"farid", "password":"passfarid" } 

我很感激这个问题的任何帮助。

来自GsonBuilder javadocs …您可以使用GsonBuilder构建您的Gson实例,并选择将null值序列化为:

  Gson gson = new GsonBuilder() .serializeNulls() .create(); 

不太熟悉Gson,但我不认为Gson会将空值写入json文件。 如果你初始化id像:

 String id = ""; 

你可能会在那里得到一个空字符串。 但是你不会在.xml文件中获得空值。

即使为null,如何强制输出值的示例。 它将输出空字符串(或“{}”,如果是对象)而不是null并忽略瞬态:

 package unitest; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; public class TheResponse { private String status; private String message; private T data; transient private String resource; public static void main(String[] args) { TheResponse foo = new TheResponse(); //TheResponse foo = new TheResponse(); foo.status = "bar"; foo.data = "baz"; Gson gson = new GsonBuilder().registerTypeAdapter(TheResponse.class, new GenericAdapter()).create(); System.out.println(gson.toJson(foo).toString()); } public static class GenericAdapter extends TypeAdapter { @Override public void write(JsonWriter jsonWriter, Object o) throws IOException { recursiveWrite(jsonWriter, o); } private void recursiveWrite(JsonWriter jsonWriter, Object o) throws IOException { jsonWriter.beginObject(); for (Field field : o.getClass().getDeclaredFields()) { boolean isTransient = Modifier.isTransient(field.getModifiers()); if (isTransient) { continue; } Object fieldValue = null; try { field.setAccessible(true); fieldValue = field.get(o); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } jsonWriter.name(field.getName()); if (fieldValue != null && fieldValue.getClass() != String.class) { recursiveWrite(jsonWriter, fieldValue); continue; } if (fieldValue == null) { if (field.getType() == String.class) jsonWriter.value(""); else { jsonWriter.jsonValue("{}"); } } else { jsonWriter.value(fieldValue.toString()); } } jsonWriter.endObject(); } @Override public Object read(JsonReader jsonReader) throws IOException { // todo return null; } } }