Gson ignores my fields while converting

前端 未结 3 485
傲寒
傲寒 2021-01-29 09:25

I created a model:

public class UserRequest extends DefaultRequest {
    public String username;
    public String password;
    public String id;

    public Us         


        
相关标签:
3条回答
  • 2021-01-29 09:47

    from the GsonBuilder javadocs... you can use GsonBuilder to construct your Gson instance, and opt in to have null values serialized as so:

     Gson gson = new GsonBuilder()
         .serializeNulls()
         .create();
    
    0 讨论(0)
  • 2021-01-29 09:47

    Not too familiar with Gson, but I don't think Gson would write null values to an json file. If you initialize the id like:

    String id = "";
    

    you may get an empty string in there. But you will not get a null value into a .xml file.

    0 讨论(0)
  • 2021-01-29 09:59

    An example of how to enforce outputting values even if null. It will output the empty string (or "{}" if an object) instead of null and ignore transients:

    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;
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题