【问题标题】:Gson ignores my fields while convertingGson 在转换时忽略了我的字段
【发布时间】:2017-05-19 12:52:26
【问题描述】:

我创建了一个模型:

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"
} 

我将不胜感激有关此问题的任何帮助。

【问题讨论】:

标签: java android json gson


【解决方案1】:

GsonBuilder javadocs...您可以使用GsonBuilder 来构造您的Gson 实例,并选择将空值按如下方式序列化:

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

【讨论】:

  • @pvg,已经指出,它解决了我的问题。无论如何,接受它,因为它以正确的方式回答了我的问题;)
【解决方案2】:

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

String id = "";

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

【讨论】:

  • 获取"" 没问题,但我没有将该字段转换为json。这就是问题所在。
  • Gson 不会将空值写入文件。因此,如果它为 null,则不会写入该字段。
【解决方案3】:

如何强制输出值(即使为 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<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;
        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多