Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert static variables in class to json

Tags:

java

json

gson

Hi I have a class Constants that contain only static variables.public class Constants

public class Constant
{
    public static class A
    {
        public static class B
        {
            public static final int  COLUMN = 0;
            public static final String  TYPE =  ColumnType.INPUT;
        }
    }
}

Is there a way to convert this class to JSON ?

I was using gson, but apparently it ignores static variables. So how can I do it ?
Thanks.

like image 281
Dany Y Avatar asked Feb 27 '13 15:02

Dany Y


People also ask

Can you change a static variable in a class?

The static methods of a particular class can only access the static variables and can change them. A static method can only call other static methods. Static methods can't refer to non-static variables or methods.

Can we reassign value to static variable?

Static methods cannot access or change the values of instance variables, but they can access or change the values of static variables.

When to use static field c#?

Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances. Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

How do you assign a value to a static variable?

Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks. Static variables can be accessed by calling with the class name ClassName. VariableName.


2 Answers

The accepted answer is correct. For clarity here is a working example. You can use the GsonBuilder class with the method excludeFieldsWithModifiers.

    GsonBuilder gsonBuilder  = new GsonBuilder();
    // Allowing the serialization of static fields
    gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
    // Creates a Gson instance based on the current configuration
    Gson gson = gsonBuilder.create();
    String json = gson.toJson(objectToSerialize);
    System.out.println(json);
like image 149
Kevin Avatar answered Oct 06 '22 17:10

Kevin


You can configure which field modifiers GSON ignores with this method on the GsonBuilder class.

like image 21
Larry Shatzer Avatar answered Oct 06 '22 19:10

Larry Shatzer