@SuppressWarnings({"unchecked"})
  public <T> T deserialize(InputStream stream, Class<T> clazz) throws IOException {
    if (isValid(clazz) == false)
      throw new IllegalArgumentException("Not a JSONAware class: " + clazz);

    try {
      JSONTokener tokener = createTokener(stream);
      JSONArray value = new JSONArray(tokener);
      T instance = clazz.newInstance();
      Collection<JSONAware> collection = (Collection<JSONAware>) instance;
      for (int i = 0; i < value.length(); i++) {
        JSONAware ja = instanceProvider.createInstance(i);
        ja.readJSONObject(value.getJSONObject(i));
        collection.add(ja);
      }
      return instance;
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      IOException ioe = new IOException();
      ioe.initCause(e);
      throw ioe;
    } finally {
      stream.close();
    }
  }
示例#2
0
 /**
  * Encode a JSON value
  *
  * @param value JSON value
  * @param sb String builder
  * @throws CharConversionException Invalid Unicode character in string value
  * @throws UnsupportedEncodingException Unsupported data type
  */
 @SuppressWarnings("unchecked")
 public static void encodeValue(Object value, StringBuilder sb)
     throws CharConversionException, UnsupportedEncodingException {
   if (value == null) {
     sb.append("null");
   } else if (value instanceof String) {
     sb.append('\"');
     escapeString((String) value, sb);
     sb.append('\"');
   } else if (value instanceof Double) {
     if (((Double) value).isInfinite() || ((Double) value).isNaN()) sb.append("null");
     else sb.append(value.toString());
   } else if (value instanceof Float) {
     if (((Float) value).isInfinite() || ((Float) value).isNaN()) sb.append("null");
     else sb.append(value.toString());
   } else if (value instanceof Number) {
     sb.append(value.toString());
   } else if (value instanceof Boolean) {
     sb.append(value.toString());
   } else if (value instanceof JSONAware) {
     ((JSONAware) value).toJSONString(sb);
   } else if (value instanceof Map) {
     encodeObject((Map<Object, Object>) value, sb);
   } else if (value instanceof List) {
     encodeArray((List<Object>) value, sb);
   } else {
     throw new UnsupportedEncodingException("Unsupported JSON data type");
   }
 }
  @SuppressWarnings({"unchecked"})
  public void serialize(Object instance, Writer writer) throws IOException {
    if (instance instanceof Collection == false)
      throw new IllegalArgumentException("Not a collection: " + instance);

    Collection<JSONAware> collection = (Collection<JSONAware>) instance;
    JSONArray jarray = new JSONArray();
    try {
      for (JSONAware elt : collection) {
        JSONObject jsonObject = createObject();
        elt.writeJSONObject(jsonObject);
        jarray.put(jsonObject);
      }
      writeArray(jarray, writer);
    } catch (JSONException e) {
      IOException ioe = new IOException();
      ioe.initCause(e);
      throw ioe;
    }
  }
  @Override
  public void handle(RequestContext ctx, JSONAware result) throws IOException {
    HttpServletRequest request = ctx.getRequest();
    HttpServletResponse response = ctx.getResponse();

    if (result == null) {
      JSONObject json = new JSONObject();
      Enumeration<String> e = request.getAttributeNames();

      while (e.hasMoreElements()) {
        String name = e.nextElement();
        json.put(name, request.getAttribute(name));
      }

      for (Map.Entry<String, Object> entry : ctx.getModel().entrySet()) {
        json.put(entry.getKey(), entry.getValue());
      }

      result = json;
    }

    String characterEncoding = request.getCharacterEncoding();
    response.setCharacterEncoding(characterEncoding);

    String mimetype = MimetypeUtils.getJSON(request);
    response.setContentType(mimetype + "; charset=" + characterEncoding);

    // jsonp callback
    String callback = ctx.getParameter("callback");

    PrintWriter out = response.getWriter();
    if (callback != null) {
      out.write(callback + '(' + result.toJSONString() + ')');
    } else {
      out.write(result.toJSONString());
    }
    out.flush();
  }