简体   繁体   English

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

[英]Convert Java object to JSON string using gson

In Java I have object that contains an List of object and each object in List Contains EncryptedInteger object 在Java中,我有一个包含一个对象列表的对象,并且列表中的每个对象都包含EncryptedInteger对象

Vote.java 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 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;

    }}

I am using this EncryptedInteger 我正在使用此EncryptedInteger

When I want to convert the object to Json using Gson it show this error 当我想使用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)

Another example that show the same error : 另一个显示相同错误的示例:

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();
        }

    }

Can you help me specifying the error and how to solve it ? 您能帮我指定错误以及如何解决吗?

Note: I doubled check I am Using Gson 2.2.4 注意:我检查了我是否正在使用Gson 2.2.4,

The version of EncryptedInteger you link to isn't the one you're using. 您链接到的EncryptedInteger版本不是您使用的版本。

The one you're using is this one (The current version). 您正在使用的是版本(当前版本)。

The difference is that it includes this line: 区别在于它包括以下行:

private Class bigi;

And it assigns BigInteger.class to it. 并将BigInteger.class分配给它。

Gson can't serialize that, and that's what is throwing that exception. Gson无法序列化它,这就是引发该异常的原因。

You're going to have to write a custom serializer / deserializer to handle that class. 您将必须编写一个自定义的序列化器/反序列化器来处理该类。 The section for this in the Gson user guide should get you started. Gson用户指南中有关此部分的内容将帮助您入门。 There's also numerous questions/answers on SO covering the subject. 关于SO的主题也有很多问题/答案。

Edit from comments: 编辑评论:

I didn't look at it much further. 我没有进一步研究。 Looking at it now, I mean, it uses that for something. 现在看,我的意思是,它它来做某事。 It also holds an instance of java.util.Random . 它还拥有java.util.Random的实例。

Looking at it a little more in-depth ... you kind of have a problem serializing/deserializing it the way it sits. 对其进行更深入的研究……您可能会遇到问题,即按其放置方式对它进行序列化/反序列化。 There's no constructor or public method to set the encrypted value. 没有构造函数或公共方法来设置加密值。 The method that would be useful for that is private ( setCipherVal() ). 对此有用的方法是privatesetCipherVal() )。 If that were public you could just write a serializer that outputs JSON holding the PublicKey and the encrypted value, then in your deserializer use those to create a new EncryptedInteger . 如果这是你公众可以只写输出JSON拿着一个串行PublicKey和加密值,然后在你的解串器使用它们来创建一个新的EncryptedInteger

Without changing that class to allow for that I don't see a way to serialize/deserialize it to JSON. 没有更改该类以允许这样做,我看不到将其序列化/反序列化为JSON的方法。

Last edit: Actually, you could , it's just ugly because you have to use reflection to set the cipherval directly after constructing the EncryptedInteger with just the PublicKey 最后编辑:其实,你可以 ,因为你必须使用反射来设置只是丑陋cipherval建设后直接EncryptedInteger只用PublicKey

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

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