3

我正在尝试使用 GSON 将列表格式的 java 对象转换为 JSON,我尝试了几种方法,但遇到了同样的错误。

第一次尝试

List<Techinv> techs = UserUtil.getTechModels(group, org);
Gson gson = new Gson();
String json = gson.toJson(techs); 

第二次尝试

List<Techinv> techs = UserUtil.getTechModels(group, org);
Type listType = new TypeToken<List<Techinv>>() {}.getType();
Gson gson = new Gson();
String json = gson.toJson(techs, listType);

第三次尝试

List<Techinv> techs = UserUtil.getTechModels(group, org);
GsonBuilder gsonBuilder = new GsonBuilder();

new GraphAdapterBuilder()
    .addType(Techinv.class)
    .registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
String json = gson.toJson(techs);

以上所有都失败了,astackoverflow error或 a can't convert java int(我的 Techinv 类中的成员之一)到 java 向量,都在 GSON 库中。

请告诉我,我在所有这些示例中都遗漏了一些简单的东西:)

技术类(如果需要)

package org.cchit.inv.model;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


/**
 * The persistent class for the techinv database table.
 * 
 */
@Entity
@NamedNativeQueries ({
    @NamedNativeQuery(name="Techinv.deleteByOrgId",
            query="DELETE FROM techinv where org_id = ?")
})
@NamedQueries ({
    @NamedQuery(name="Techinv.removeUser",
            query="UPDATE Techinv t SET user_id = 0 where t.id = :techid"),
    @NamedQuery(name="Techinv.getAllByOrg",
            query="SELECT p FROM Techinv p where p.organization.liferayId = :orgid"),
    @NamedQuery(name="Techinv.getById",
            query="SELECT t FROM Techinv t where t.id = :id"),
    @NamedQuery(name="Techinv.getByProdOrg",
            query="SELECT p FROM Techinv p where p.organization.liferayId = :orgid and p.product.id = :prodid"),
    @NamedQuery(name="Techinv.delete",
            query="DELETE FROM Techinv t where t.id = :id")
    })
@Table(name="techinv")
public class Techinv implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @Column(name="mu_mask")
    private long muMask;

    @Column(name="mu_assigned_mask")
    private long muAssignedMask;

    @Column(name="mu_asked_assign_mask")
    private long muAskedAssignedMask;

    @Column(name="mu_cert_mask")
    private long muWillCertMask;

    @Column(name="mu_ask_will_cert_mask")
    private long muAskedWillCertMask;

    @Column(name="certType")
    private String certType;

    @Temporal(TemporalType.DATE)
    @Column(name="Apply_date")
    private Date applyDate;

    @Temporal(TemporalType.DATE)
    @Column(name="Cert_date")
    private Date certDate;

    @Lob()
    private String notes;

    //bi-directional many-to-one association to OrgUser
    @ManyToOne
    @JoinColumn(name="user_id")
    private OrgUser orgUser;

    //bi-directional many-to-one association to Organization
    @ManyToOne
    @JoinColumn(name="org_id")
    private Organization organization;

    //bi-directional many-to-one association to Product
    @ManyToOne
    @JoinColumn(name="prod_id")
    private Product product;

    //bi-directional many-to-one association to Certification
    @ManyToOne
    @JoinColumn(name="cert_id")
    private Certification certification;

    public void setCertification(Certification certification) {
        this.certification = certification;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public Techinv() {
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNotes() {
        return this.notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    public OrgUser getOrgUser() {
        return this.orgUser;
    }

    public void setOrgUser(OrgUser orgUser) {
        this.orgUser = orgUser;
    }

    public Organization getOrganization() {
        return this.organization;
    }

    public void setOrganization(Organization organization) {
        this.organization = organization;
    }

    public long getMuMask() {
        return muMask;
    }

    public void setMuMask(long muMask) {
        this.muMask = muMask;
    }

    public long getMuAssignedMask() {
        return muAssignedMask;
    }

    public void setMuAssignedMask(long muAssigned) {
        this.muAssignedMask = muAssigned;
    }

    public Certification getCertification() {
        return certification;
    }

    public long getMuWillCertMask() {
        return muWillCertMask;
    }

    public void setMuWillCertMask(long muWillCertMask) {
        this.muWillCertMask = muWillCertMask;
    }

    public long getMuAskWillCertMask() {
        return muAskedWillCertMask;
    }

    public void setMuAskedWillCertMask(long muAskedWillCertMask) {
        this.muAskedWillCertMask = muAskedWillCertMask;
    }

    /**
     * This will set the question to true. Once asked and answered, this cannot be unset.
     * @param mu
     */
    public void setMuAskedAssignedMask(Mu mu) {
        this.muAskedAssignedMask |= mu.getMask();
    }

    public boolean isCertified(Mu mu) {
        return getCertification() != null && (getCertification().getMuMask() & mu.getMask()) > 0;
    }

    public boolean isAssigned(Mu mu) {
        return (getMuAssignedMask() & mu.getMask()) > 0;
    }

    public boolean hasAskedToCertify(Mu mu) {
        return isAssigned(mu) && !isCertified(mu) && (getMuAskWillCertMask() & mu.getMask()) > 0;
    }

    public boolean isWillCertify(Mu mu) {
        return hasAskedToCertify(mu) && (getMuWillCertMask() & mu.getMask()) > 0;
    }

    public boolean hasMu(Mu mu) {
        return (getMuMask() & mu.getMask()) > 0;
    }

    public boolean hasAskedToAssign(Mu mu) {
        return (muAskedAssignedMask & mu.getMask()) > 0;
    }

    public String getCertType() {
        return certType;
    }

    public void setCertType(String certType) {
        this.certType = certType;
    }

    public Date getApplyDate() {
        return applyDate;
    }

    public void setApplyDate(Date applyDate) {
        this.applyDate = applyDate;
    }

    public Date getCertDate() {
        return certDate;
    }

    public void setCertDate(Date certDate) {
        this.certDate = certDate;
    }
}
4

3 回答 3

2

You should check for circular references in your serialized classes and mark the appropriate properties @Transient. Post your TechModel class if you want help with that.

edit: as using @Transient is not an option for you , use Gson's @Expose . From the GSON user guide :

This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The Gson instance created will exclude all fields in a class that are not marked with @Expose annotation.

于 2012-10-26T19:01:29.130 回答
0
Type listType = new TypeToken<ArrayList<Techinv>>() {}.getType();
于 2012-10-26T18:59:26.413 回答
0

You may try out the standard implementation of the Java API for JSON processing which is part of J2EE.

I don't have access to your beans OrgUser, Organization, Product, and Certification. So I assume that each of them comprises an id and a name.

For your List<Techinv> techList.

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

List<Techinv> techList = new ArrayList<Techinv>();
for (int i = 1; i <= 3; i++) {
    Techinv tech = new Techinv(i, 1L, 2L, 3L, 4L, 5L, "cert",
            new Date(), new Date(), "notes", new OrgUser(i, "orguser"),
            new Organization(i, "organization"), new Product(i,
                    "product"), new Certification(i, "certification"));
    techList.add(tech);
}
Techinv[] techArr = techList.toArray(new Techinv[techList.size()]);

JsonArrayBuilder techArrBuilder = Json.createArrayBuilder();
for (Techinv tech : techArr) {
    JsonObjectBuilder jsonObject = Json.createObjectBuilder()
        .add("id", tech.getId())
        .add("muMask", tech.getMuMask())
        .add("muAssignedMask", tech.getMuAssignedMask())
        .add("muAskedAssignedMask", tech.getMuAskedAssignedMask())
        .add("muWillCertMask", tech.getMuWillCertMask())
        .add("muAskedWillCertMask", tech.getMuAskedWillCertMask())
        .add("certType", tech.getCertType())
        .add("applyDate", sdf.format(tech.getApplyDate()))
        .add("certDate", sdf.format(tech.getCertDate()))
        .add("notes", tech.getNotes())

        .add("OrgUser", Json.createObjectBuilder()
        .add("id", tech.getOrgUser().getId())
        .add("name", tech.getOrgUser().getName()))

        .add("Organization", Json.createObjectBuilder()
        .add("id", tech.getOrganization().getId())
        .add("name", tech.getOrganization().getName()))

        .add("Product", Json.createObjectBuilder()
        .add("id", tech.getProduct().getId())
        .add("name", tech.getProduct().getName()))

        .add("Certification", Json.createObjectBuilder()
        .add("id", tech.getCertification().getId())
        .add("name", tech.getCertification().getName()));
    techArrBuilder.add(jsonObject);
}
JsonArray jsonArray = techArrBuilder.build();

Map<String, Object> prop = new HashMap<String, Object>() {
    {
        put(JsonGenerator.PRETTY_PRINTING, true);
    }
};
JsonWriter jsonWriter = Json.createWriterFactory(prop).createWriter(System.out);
jsonWriter.writeArray(jsonArray);
jsonWriter.close();

The output should be:

[
    {
        "id":1,
        "muMask":1,
        "muAssignedMask":2,
        "muAskedAssignedMask":3,
        "muWillCertMask":4,
        "muAskedWillCertMask":5,
        "certType":"cert",
        "applyDate":"2014-04-03",
        "certDate":"2014-04-03",
        "notes":"notes",
        "OrgUser":{
            "id":1,
            "name":"orguser"
        },
        "Organization":{
            "id":1,
            "name":"organization"
        },
        "Product":{
            "id":1,
            "name":"product"
        },
        "Certification":{
            "id":1,
            "name":"certification"
        }
    },
    {
        "id":2,
        "muMask":1,
        "muAssignedMask":2,
        "muAskedAssignedMask":3,
        "muWillCertMask":4,
        "muAskedWillCertMask":5,
        "certType":"cert",
        "applyDate":"2014-04-03",
        "certDate":"2014-04-03",
        "notes":"notes",
        "OrgUser":{
            "id":2,
            "name":"orguser"
        },
        "Organization":{
            "id":2,
            "name":"organization"
        },
        "Product":{
            "id":2,
            "name":"product"
        },
        "Certification":{
            "id":2,
            "name":"certification"
        }
    },
    {
        "id":3,
        "muMask":1,
        "muAssignedMask":2,
        "muAskedAssignedMask":3,
        "muWillCertMask":4,
        "muAskedWillCertMask":5,
        "certType":"cert",
        "applyDate":"2014-04-03",
        "certDate":"2014-04-03",
        "notes":"notes",
        "OrgUser":{
            "id":3,
            "name":"orguser"
        },
        "Organization":{
            "id":3,
            "name":"organization"
        },
        "Product":{
            "id":3,
            "name":"product"
        },
        "Certification":{
            "id":3,
            "name":"certification"
        }
    }
]
于 2014-04-03T21:46:11.793 回答