开发者

Is it possible to convert JPQL query result with multiple Object types into JSON format automatically?

开发者 https://www.devze.com 2023-02-01 05:49 出处:网络
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.

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 //he开发者_如何学JAVAre 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]] ]


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号