转换时Gson忽略了我的字段

时间:2017-05-19 12:52:26

标签: java android json 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"
} 

感谢您对此问题的任何帮助。

3 个答案:

答案 0 :(得分:3)

来自GsonBuilder javadocs的

...您可以使用GsonBuilder构建Gson实例,并选择将null值序列化为:

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

答案 1 :(得分:1)

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

String id = "";

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

答案 2 :(得分:0)

即使为null,如何强制输出值的示例。它将输出空字符串(或#34; {}"如果是对象)而不是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<T> {
    private String status;
    private String message;
    private T data;
    transient private String resource;

    public static void main(String[] args) {

        TheResponse<String> foo = new TheResponse<String>();
        //TheResponse<Baz> foo = new TheResponse<Baz>();
        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<Object> {
        @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;
        }

    }
}