简体   繁体   English

与Gson反对Json | 安卓

[英]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. 我需要将此对象转换为Json字符串,但是如果对象声明为MainActivity类,则无法。 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. 即使使用第二种方法,json变量也为null。

Button in android is not serializable. android中的按钮不可序列化。

But you could serialize the metadata(properties) of button, such as textsize,textcolor,etc. 但是您可以序列化按钮的元数据(属性),例如textsize,textcolor等。 then use these data when create button. 然后在创建按钮时使用这些数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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