How to pass gson serialised object to Intent in android?

前端 未结 3 673
南笙
南笙 2020-12-16 01:55

i am trying to pass the gson serialised object to intent by using the below code

intent.putExtra(\"com.example\", vo); // vo is the gson

相关标签:
3条回答
  • 2020-12-16 02:19

    I added implements Serializable to my model AND other models (sub-models) used by my model. Then I can pass the GSON object via Intent:

    public class MyModel implements Serializable {
        SubModel subModel;
    }
    
    public class SubModel implements Serializable {
        ...
    }
    

    In fragment:

    Intent startIntent = new Intent(getContext(), NextActivity.class);
    startIntent.putExtra("mymodel", myModelObject);
    startActivity(startIntent);
    

    In next activity:

    Intent intent = getIntent();
    MyModel mymodel = (MyModel) intent.getSerializableExtra("mymodel");
    // test if we get the model correctly:
    setTitle(mymodel.getName());
    
    0 讨论(0)
  • 2020-12-16 02:24

    When your object or Model is extend RealmObject you need to use that:

    Step1:

     Gson gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() {
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getDeclaringClass().equals(RealmObject.class);
    }
    
    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
    })
    .create();
    

    And

     intent.putExtra("userfrom",gson.toJson(obj));
    

    Step2:

    Gson gson = new GsonBuilder().create();
    
    
    
     user =gson.fromJson(getIntent().getStringExtra("userfrom"),User.class);
    

    I used this for pass data with Intent but work for retrofit

    0 讨论(0)
  • 2020-12-16 02:32

    No you are using it in the wrong way.

    Put the object in the intent as:

    Gson gson = new Gson();
    Intent intent = new Intent(Source.this, Target.class);
    intent.putExtra("obj", gson.toJson(yourObject));
    

    and get the object in another activity as:

    Gson gson = new Gson();
    String strObj = getIntent().getStringExtra("obj");
    SourceObject obj = gson.fromJson(strObj, SourceObject.class);
    
    0 讨论(0)
提交回复
热议问题