使用gson将对象转换为json时,无法访问java.lang.reflect.Method构造函数

时间:2018-01-09 00:59:14

标签: java android gson

这是我尝试使用GSON的第一次尝试。我收到了这个错误。

Can not make a java.lang.reflect.Method constructor accessible

这是我用来创建json的代码:

SoundEffects soundEffect = new SoundEffects("test", "test");
String json = new Gson().toJson(soundEffect);

这是类soundeffects = new MediaRecorder();:

   public class SoundEffects /*implements Serializable*/ {
private MediaRecorder mediaRecorder;
private String name;
private String output;

public SoundEffects(){

}

public SoundEffects(String output, String name) {
    this.output = output;
    this.name = name;
}
public String getName() {
    return this.name;
}
public void setName(String name) {
    this.name = name;
}
public String getOutput() {
    return  output;
}
public void setOutput(String output) {
    this.output = output;
}

在课堂上放置一个空构造函数并没有帮助,错误仍然存​​在。

1 个答案:

答案 0 :(得分:0)

您可以通过自定义适配器反序列化

Gson getCustomGson(){
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(SoundEffects.class, new CustomDeserializer());
    return gsonBuilder.create();
}

class CustomDeserializer implements JsonDeserializer<SoundEffects> {
    @Override
    public SoundEffects deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
           SoundEffects soundEffects = new SoundEffects();
           // do deserialize your object here
           .....
           // last, you can create the MediaRecorder and set to the object
           MedaiRecorder mediaRecorder = new MediaRecorder();
           soundEffects.setMediaRecorder(mediaRecorder);
           return soundEffects;
    }
}