简体   繁体   中英

Object to Json with Gson | ANDROID

I need to convert this object to a Json String but if the Object is declared into the MainActivity Class I cant. If i declared it into the function, it works.

public class MainActivity extends AppCompatActivity {

public class Boton implements Serializable{
    public Button bt;
    public String path;
    public String fname;
    /*Boton(Button bt, String path, String fname){
        this.bt = bt;
        this.path = path;
        this.fname = fname;
    }*/
}
Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        load_bts();
}

public void load_bts(){
        Button bt = new Button(this);
        Boton cbt = new Boton();
        cbt.bt = bt;
        cbt.path = "QUESO";
        cbt.fname = "";

        Gson gson = new Gson();
        String json = gson.toJson(cbt);
}

if I do this, The app works:

public void load_bts() {
    class Boton implements Serializable {
        public Button bt;
        public String path;
        public String fname;
    }
    Button bt = new Button(this);
    Boton cbt = new Boton();
    cbt.bt = bt;
    cbt.path = "QUESO";
    cbt.fname = "";

    Gson gson = new Gson();
    String json = gson.toJson(cbt);
}

You cannot serialize a Button. Both ways doesn't work. Even with your second method, the json variable is null.

Button in android is not serializable.

But you could serialize the metadata(properties) of button, such as textsize,textcolor,etc. then use these data when create button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM