使用gson将Java对象转换为JSON字符串

时间:2014-04-21 19:33:25

标签: java json gson biginteger

在Java中我有一个对象,其中包含一个对象List,List中的每个对象包含 EncryptedInteger 对象

Vote.java

public class Vote implements Serializable {
private static final long serialVersionUID = 2L;
private int voteId;
private int surveyId;
private int voterId;
private List<Choice> choices;
private boolean counted;


public Vote(){
}

public Vote(int surveyId,int voterId){
    this.surveyId=surveyId;
    this.voterId=voterId;
    this.choices = new ArrayList<Choice>();
    this.counted=false;
}

public Vote(int voteId,int surveyId,int voterId, boolean counted){
    this.voteId=voteId;
    this.surveyId=surveyId;
    this.voterId=voterId;
    this.choices = new ArrayList<Choice>();
    this.counted=counted;
}

public void addChoice(Choice choice) {
    choices.add(choice);
}


public String ChoicesToJson() {
    Gson gson = new Gson();
    String json = gson.toJson(this.choices);
    return json;
}


public void JsonToChoices(String json) {
    Gson gson = new Gson();
    TypeToken<List<Choice>> token = new TypeToken<List<Choice>>() {
    };
    this.choices = gson.fromJson(json, token.getType());
}
public int getVoteId() {
    return voteId;
}
public void setVoteId(int voteId) {
    this.voteId = voteId;
}
public int getSurveyId() {
    return surveyId;
}
public void setSurveyId(int surveyId) {
    this.surveyId = surveyId;
}
public int getVoterId() {
    return voterId;
}
public void setVoterId(int voterId) {
    this.voterId = voterId;
}
public List<Choice> getChoices() {
    return choices;
}
public void setChoices(List<Choice> choices) {
    this.choices = choices;
}
public boolean isCounted() {
    return counted;
}
public void setCounted(boolean counted) {
    this.counted = counted;
}}

Choice.java

 public class Choice implements Serializable {

    private static final long serialVersionUID = 3L;
    private EncryptedInteger encryptedInteger;
    private int questionNumber;
    private int optionNumber;
    private double S;

    public Choice(EncryptedInteger encryptedInteger, int questionNumber,
            int optionNumber, double s) {

        this.encryptedInteger = encryptedInteger;
        this.questionNumber = questionNumber;
        this.optionNumber = optionNumber;
        S = s;
    }

    public EncryptedInteger getEncryptedInteger() {
        return encryptedInteger;
    }

    public void setEncryptedInteger(EncryptedInteger encryptedInteger) {
        this.encryptedInteger = encryptedInteger;
    }

    public int getQuestionNumber() {
        return questionNumber;
    }

    public void setQuestionNumber(int questionNumber) {
        this.questionNumber = questionNumber;
    }

    public int getOptionNumber() {
        return optionNumber;
    }

    public void setOptionNumber(int optionNumber) {
        this.optionNumber = optionNumber;
    }

    public double getS() {
        return S;
    }

    public void setS(double s) {
        S = s;
    }

    public String encryptedtoJson() {
        Gson gson = new Gson();

        String json = gson.toJson(this.encryptedInteger);

        return json;

    }}

我正在使用此EncryptedInteger

当我想使用Gson将对象转换为Json时,它会显示此错误

java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: java.math.BigInteger. Forgot to register a type adapter?
    com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:67)
    com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
    com.google.gson.Gson.toJson(Gson.java:593)
    com.google.gson.Gson.toJson(Gson.java:572)
    com.google.gson.Gson.toJson(Gson.java:527)
    recieving.request.server.GenerateNumberRequest.GNA(GenerateNumberRequest.java:151)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

显示相同错误的另一个示例:

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PrivateKey prk=new PrivateKey(1024);
        PublicKey pup= prk.getPublicKey();

        try {
            EncryptedInteger e=new EncryptedInteger(BigInteger.ONE, pup);
            Gson gson=new Gson();
System.out.println(gson.toJson(e));
  } catch (BigIntegerClassNotValid e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

您能帮我指出错误以及解决方法吗?

注意:我加倍检查我正在使用Gson 2.2.4

1 个答案:

答案 0 :(得分:1)

您链接到EncryptedInteger版本不是您正在使用的版本。

您正在使用的是this one(当前版本)。

不同之处在于它包含以下这一行:

private Class bigi;

并为其分配BigInteger.class

Gson无法将其序列化,这就是抛出异常的原因。

您将不得不编写自定义序列化程序/反序列化程序来处理该类。 section for this in the Gson user guide应该让你入门。关于这个主题的SO也有很多问题/答案。

根据评论进行修改:

我没有进一步看待它。现在看它,我的意思是,使用来做某些事情。它还包含java.util.Random的实例。

更深入地看一下......你有一个问题就是按照它的方式序列化/反序列化它。没有构造函数或公共方法来设置加密值。对此有用的方法是privatesetCipherVal())。如果这是公开的,您可以编写一个输出JSON的序列化程序,其中包含PublicKey和加密值,然后在您的反序列化程序中使用这些来创建新的EncryptedInteger

不改变该类以允许这种情况我没有看到将它序列化/反序列化为JSON的方法。

上次修改:实际上,你可以,这只是丑陋,因为在构建{{1}后你必须使用反射来直接设置cipherval仅使用EncryptedInteger