是否可以将多种Object类型的JPQL查询结果自动转换为JSON格式?

发布于 2024-10-08 18:36:39 字数 2508 浏览 2 评论 0原文

我正在使用 JPA Toplink、JAX-RS、NetBean6.9

到目前为止,我成功地将 JPQL 查询结果(具有一种对象类型的 List)转换为 JSON。 以下工作正常,它在到达浏览器时生成 JSON,因为我在 JPA 注释中指定了

JPA snippet

@XmlRootElement //here enable JSON
@Entity
@Table(name = "MasatosanTest")

Resource class snippet

@Path("allJoin")
    @GET
    @Produces("application/json")
    public List<MasatosanTest> getAllJoinResult() {

        EntityManager em = null;
        List<Object[]> mt = null;

        try {
            em = EmProvider.getDefaultManager();

            Query query = em.createQuery("SELECT m1, m2 FROM MasatosanTest m1, MasatosanTest2 m2");

            mt = query.getResultList();
        }
        catch(Exception e) {
            System.out.println("MasatosanTestResource.java - getJoinedResult ERROR: " + e);
        }
        finally {
            if(em != null) {
                em.close();
            }
        }

        //I'm only adding MasatosanTest object into the List not MasatosanTest2
        List<MasatosanTest> list = new ArrayList<MasatosanTest>();
        MasatosanTest mt = null;
        for(Object[] items : mt) {
            mt = (MasatosanTest)items[0];
            list.add(mt);
        }
        return list;
    }//end getAllJoinResult()

浏览器中上面的代码将输出一些内容比如:

[MasatosanTest : [[name:foo], [name:moo]]

我的问题是,当 JPQL 返回 2 个不同的对象类型时,它不会再自动转换为 JSON。

如果我稍微修改一下上面的代码,我也会将 MasatosanTest2 添加到列表中。

 //Now I'm adding MasatosanTest2 to the List in addition to MasatosanTest
 //So changing List data type to List<Object> to accept both object types.
        List<Object> list = new ArrayList<Object>();
        MasatosanTest mt = null;
        MasatosanTest2 mt2 = null;
        for(Object[] items : mt) {

            mt = (MasatosanTest)items[0];
            mt2 = (MasatosanTest2)items[1];
            list.add(mt);
            list.add(mt2)
        }
        return list;

然后当然也将方法返回类型更改为 List。

 public List<Object> getAllJoinResult() {

然后我收到一个错误,抱怨它不能是 JSON :(

 A message body writer for Java type, class java.util.ArrayList, 
and MIME media type, application/json, was not found

是否允许包含多种类型的 JSON?

我的目标是拥有如下 JSON:

[[MasatosanTest : [[name:foo], [name:moo]],
[MasatosanTest2 : [[name:boo], [name:www]] ]

I'm using JPA Toplink, JAX-RS, NetBean6.9

So far I successfully convert JPQL query result which is List with one object type into JSON.
Following works fine, it generates JSON by the time it gets to the browser because I specified so in JPA annotation

JPA snippet

@XmlRootElement //here enable JSON
@Entity
@Table(name = "MasatosanTest")

Resource class snippet

@Path("allJoin")
    @GET
    @Produces("application/json")
    public List<MasatosanTest> getAllJoinResult() {

        EntityManager em = null;
        List<Object[]> mt = null;

        try {
            em = EmProvider.getDefaultManager();

            Query query = em.createQuery("SELECT m1, m2 FROM MasatosanTest m1, MasatosanTest2 m2");

            mt = query.getResultList();
        }
        catch(Exception e) {
            System.out.println("MasatosanTestResource.java - getJoinedResult ERROR: " + e);
        }
        finally {
            if(em != null) {
                em.close();
            }
        }

        //I'm only adding MasatosanTest object into the List not MasatosanTest2
        List<MasatosanTest> list = new ArrayList<MasatosanTest>();
        MasatosanTest mt = null;
        for(Object[] items : mt) {
            mt = (MasatosanTest)items[0];
            list.add(mt);
        }
        return list;
    }//end getAllJoinResult()

The code above in the browser will output something like:

[MasatosanTest : [[name:foo], [name:moo]]

My problem is when 2 different Object types are returned by JPQL, it won't convert to JSON automatically anymore.

If I modify the code above a bit where I'm adding MasatosanTest2 to list as well.

 //Now I'm adding MasatosanTest2 to the List in addition to MasatosanTest
 //So changing List data type to List<Object> to accept both object types.
        List<Object> list = new ArrayList<Object>();
        MasatosanTest mt = null;
        MasatosanTest2 mt2 = null;
        for(Object[] items : mt) {

            mt = (MasatosanTest)items[0];
            mt2 = (MasatosanTest2)items[1];
            list.add(mt);
            list.add(mt2)
        }
        return list;

Then of course change method return type to List too.

 public List<Object> getAllJoinResult() {

Then I get an error complaining it can't be JSON :(

 A message body writer for Java type, class java.util.ArrayList, 
and MIME media type, application/json, was not found

Is it allowed to have JSON that contains multiple types?

My goal is to have JSON like:

[[MasatosanTest : [[name:foo], [name:moo]],
[MasatosanTest2 : [[name:boo], [name:www]] ]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初熏 2024-10-15 18:36:39

根据网上其他人的帮助测试了一下,我发现返回的查询结果是List,而这个Object[]实际上是Vector< /代码>。

所以,下面的工作就完成了(但不确定是否足够有效)
JSONStringer 也来自 jettison api。

  List<Object[]> out = null;
  JSONStringer jstr = null;
  sb = new StringBuilder();
  Vector vec = null;
      for(Object item : out) {
          vec = (Vector)item;

          jstr = new JSONStringer();
          String json = jstr.object()
               .key("columnName1").value( vec.get(0) )
               .key("columnName2").value( vec.get(1) )
               .key("columnName3").value( vec.get(2) )
               .key("columnName4").value( vec.get(3) )
               .key("columnName5").value( vec.get(4) )
                    .endObject().toString();

                sb.append(json).append(",");
                jstr = null;//reset
       }

   sb.deleteCharAt(sb.length() - 1);
   System.out.println("====== json out result =====> " + sb.toString());

After testing few based on other people's help online, I figured that returned query result is List<Object[]> and this Object[] is actually Vector.

So, below would do the job (not sure if efficient enough though)
Also JSONStringer is from jettison api.

  List<Object[]> out = null;
  JSONStringer jstr = null;
  sb = new StringBuilder();
  Vector vec = null;
      for(Object item : out) {
          vec = (Vector)item;

          jstr = new JSONStringer();
          String json = jstr.object()
               .key("columnName1").value( vec.get(0) )
               .key("columnName2").value( vec.get(1) )
               .key("columnName3").value( vec.get(2) )
               .key("columnName4").value( vec.get(3) )
               .key("columnName5").value( vec.get(4) )
                    .endObject().toString();

                sb.append(json).append(",");
                jstr = null;//reset
       }

   sb.deleteCharAt(sb.length() - 1);
   System.out.println("====== json out result =====> " + sb.toString());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文