0

I have the following class, and I do output the objects of the class in Json string format:

public final class MyClass {

    private String field1 = null;
    private String field2 = null;

    @Override
    public final String toString() {
        return toJsonString();
    }

    public final String toJsonString() {
        return (new Gson()).toJson(this);
    }

    :
    :

    public static void main(String[] args) {

        MyClass a = new MyClass();
        a.field1 = "Hello";

        System.out.println(a);
    }

}

The above code, the main program output is below:

{"field1":"Hello"}

Is it possible to make it output:

{"field1":"Hello", "field2":null}

Thanks!

1 Answer 1

1

The default configuration for Gson ignores nulls, but you can use GsonBuilder to change that:

Gson gson = new GsonBuilder().serializeNulls().create();
return gson.toString(this);

The user guide describes this, and the javadocs describe the other options GsonBuilder gives you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.