A generic JSON response returning an object. Status code is always {@code 200}.
@param response the response to write to
@param obj an object
162907
public static void returnObjectResponse(HttpServletResponse response, Object obj) {
		if (response == null) {
			return;
		}
		PrintWriter out = null;
		try {
			response.setStatus(HttpServletResponse.SC_OK);
			response.setContentType(MediaType.APPLICATION_JSON);
			out = response.getWriter();
			ParaObjectUtils.getJsonWriter().writeValue(out, obj);
		} catch (Exception ex) {
			logger.error(null, ex);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
363429
public static <T> GenericResponseBuilder<T> status(Response.Status status) {
    return status((Response.StatusType) status);
  }
11486
function serverResponseToRESPONSE (response) {
	try {
		const obj = JSON.parse(response);
		if (obj.result === RESPONSE_UNKNOWN) {
			return RESPONSE_UNKNOWN;
		} else {
			return obj.result.result;
		}
	} catch (e) {
		return RESPONSE_INVALID;
	}
}
48383
private JsonArray getJsonFromResponse(HttpResponse response) throws IOException
    {
        InputStream content = response.getEntity().getContent();
        Reader reader = new InputStreamReader(content);
        JsonObject json = gson.fromJson(reader, JsonObject.class);
        JsonElement jsonElement = json.get("rows");
        return jsonElement == null ? null : jsonElement.getAsJsonArray();
    }
455558
public static boolean checkResponseStatus(JSONObject jsonResponse) {

        if (jsonResponse != null) {

            if (jsonResponse.getBoolean("ok")) {

                return true;
            } else {

                System.err.println("The API returned the following error: " + jsonResponse.getString("description"));
            }
        } else {

            System.err.println("JSON Response was null, something went wrong...");
        }

        return false;
    }
2690
private void processBatchRequestResponse(CloseableHttpResponse response) throws IOException,
      UnexpectedResponseException {
    String entityStr = EntityUtils.toString(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode >= 400) {
      throw new RuntimeException("Failed due to " + entityStr + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }

    JsonObject jsonBody = new JsonParser().parse(entityStr).getAsJsonObject();
    if (!jsonBody.get("hasErrors").getAsBoolean()) {
      return;
    }

    JsonArray results = jsonBody.get("results").getAsJsonArray();
    for (JsonElement jsonElem : results) {
      JsonObject json = jsonElem.getAsJsonObject();
      int subStatusCode = json.get("statusCode").getAsInt();
      if (subStatusCode < 400) {
        continue;
      } else if (subStatusCode == 400
                 && Operation.INSERT_ONLY_NOT_EXIST.equals(operation)) {
        JsonElement resultJsonElem = json.get("result");
        Preconditions.checkNotNull(resultJsonElem, "Error response should contain result property");
        JsonObject resultJsonObject = resultJsonElem.getAsJsonArray().get(0).getAsJsonObject();
        if (isDuplicate(resultJsonObject, subStatusCode)) {
          continue;
        }
      }
      throw new RuntimeException("Failed due to " + jsonBody + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }
  }
707912
def json_response(data, status=200, serializer=None):
    
    return HttpResponse(json.dumps(data, default=serializer),
                        status=status,
                        content_type='application/json; charset=UTF-8')
199004
def json(
    body,
    status=200,
    headers=None,
    content_type="application/json",
    dumps=json_dumps,
    **kwargs
):
    
    return HTTPResponse(
        dumps(body, **kwargs),
        headers=headers,
        status=status,
        content_type=content_type,
    )
641924
protected void handleJSONMessageAsDummy(JSONObject obj) throws Exception {
        hostLog.info("Generating dummy response for ops request " + obj);
        sendOpsResponse(null, obj, OPS_DUMMY);
    }
434609
private static Response createResponse(Object object) {
    if (object == null) {
      return Response.ok().build();
    }

    if (object instanceof Response) {
      return (Response) object;
    }

    if (object instanceof Response.Status) {
      Response.Status s = (Response.Status) object;
      switch (s) {
        case OK:
          return Response.ok().build();
        case ACCEPTED:
          return Response.accepted().build();
        case NO_CONTENT:
          return Response.noContent().build();
        default:
          return createErrorResponse(
              new S3Exception("Response status is invalid", S3ErrorCode.INTERNAL_ERROR));
      }
    }

    // Need to explicitly encode the string as XML because Jackson will not do it automatically.
    XmlMapper mapper = new XmlMapper();
    try {
      return Response.ok(mapper.writeValueAsString(object)).build();
    } catch (JsonProcessingException e) {
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
          .entity("Failed to encode XML: " + e.getMessage()).build();
    }
  }
78339
public <T> Response<T> toJsonResponse(Class<T> cls) {
        return new Response<>(this.url, this.statusCode, this.cookies, this.headers, readToJson(cls));
    }
1228077
void writeObject(java.io.ObjectOutputStream out) throws IOException {
        // when using object serialization, write the json bytes
        byte[] bytes = toString().getBytes(StandardCharsets.UTF_8);
        out.writeInt(bytes.length);
        out.write(bytes);
    }
475758
def jsonify(obj, status=200, headers=None):
    
    data = JSONEncoder().encode(obj)
    if 'callback' in request.args:
        cb = request.args.get('callback')
        data = '%s && %s(%s)' % (cb, cb, data)
    return Response(data, headers=headers, status=status,
                    mimetype='application/json')
557855
protected Object readResponse(Type returnType, JsonNode jsonObject) throws Throwable {
		return readResponse(returnType, jsonObject, null);
	}
757472
function onResponse( response ) {
		if ( response.statusCode !== 200 ) {
			err = {
				'status': response.statusCode,
				'message': ''
			};
		}
		debug( 'Received a response from query endpoint.' );
		debug( 'Response status: %s.', response.statusCode );
		debug( 'Response headers: %s', JSON.stringify( response.headers ) );

		response.setEncoding( 'utf8' );
		response.on( 'data', onData );
		response.on( 'end', onEnd );
	}
925464
@SuppressWarnings("unchecked")
    public static void after(Object request, Object response) {

        HttpData data = new HttpData();

        /*
         * Use reflection to access the HttpServletRequest/Response as using the
         * true method signature caused ClassLoader issues.
         */
        Class<?> reqClass = request.getClass();
        Class<?> respClass = response.getClass();
        try {
            /*
             * Retrieve the request tracker
             */
            Method getAttribute = reqClass.getMethod(GET_ATTRIBUTE, String.class);
            Method setAttribute = reqClass.getMethod(SET_ATTRIBUTE, String.class, Object.class);
            HttpRequestTracker tracker = (HttpRequestTracker) (getAttribute.invoke(request, TRACKER_ATTRIBUTE));
            if (tracker == null) {
                /*
                 * should never happen
                 */
                throw new JavametricsException("Unable to find request tracker");
            }

            /*
             * Decrement the nesting level and return if still nested
             */
            if (tracker.decrement()) {
                setAttribute.invoke(request, TRACKER_ATTRIBUTE, tracker);
                return;
            }

            /*
             * Clear the tracker
             */
            setAttribute.invoke(request, TRACKER_ATTRIBUTE, null);

            data.setRequestTime(tracker.getRequestTime());

            Method getRequestURL = reqClass.getMethod(GET_REQUEST_URL);
            data.setUrl(((StringBuffer) getRequestURL.invoke(request)).toString());

            Method getMethod = reqClass.getMethod(GET_METHOD);
            data.setMethod((String) getMethod.invoke(request));

            Method getStatus = respClass.getMethod(GET_STATUS);
            data.setStatus((Integer) getStatus.invoke(response));

            if (detailed) {
                Method getContentType = respClass.getMethod(GET_CONTENT_TYPE);
                data.setContentType((String) getContentType.invoke(response));

                Method getHeaders = respClass.getMethod(GET_HEADER_NAMES);
                Method getHeader = respClass.getMethod(GET_HEADER, String.class);
                Collection<String> headers = (Collection<String>) getHeaders.invoke(response);
                if (headers != null) {
                    for (String headerName : headers) {
                        String header = (String) getHeader.invoke(response, headerName);
                        if (header != null) {
                            data.addHeader(headerName, header);
                        }
                    }
                }

                Method getReqHeaders = reqClass.getMethod(GET_HEADER_NAMES);
                Method getReqHeader = reqClass.getMethod(GET_HEADER, String.class);
                Enumeration<String> reqHeaders = (Enumeration<String>) getReqHeaders.invoke(request);
                if (reqHeaders != null) {
                    while (reqHeaders.hasMoreElements()) {
                        String headerName = reqHeaders.nextElement();
                        String header = (String) getReqHeader.invoke(request, headerName);
                        if (header != null) {
                            data.addRequestHeader(headerName, header);
                        }
                    }
                }
            }
            
            data.setDuration(System.currentTimeMillis() - tracker.getRequestTime());

            if (Agent.debug) {
                System.err.println("Javametrics: Sending {\"http\":" + data.toJsonString() + "}");
            }

            /*
             * Send the http request data to the Javametrics agent
             */
            Javametrics.getInstance().sendJSON(HTTP_TOPIC, data.toJsonString());

        } catch (Exception e) {
            // Log any exception caused by our injected code
            System.err.println("Javametrics: Servlet callback exception: " + e.toString());
            e.printStackTrace();
        }

    }
14328
public static void writeObjectInstanceOutput(final RESTResponse response, final ObjectInstanceWrapper value, final JSONConverter converter) {
        response.setContentType(APIConstants.MEDIA_TYPE_APPLICATION_JSON);

        OutputStream outStream = null;
        try {
            outStream = response.getOutputStream();

            //Converter the value
            converter.writeObjectInstance(outStream, value);

            //Return converter
            JSONConverter.returnConverter(converter);

            outStream.flush();
        } catch (Exception e) {
            throw ErrorHelper.createRESTHandlerJsonException(e, converter, APIConstants.STATUS_INTERNAL_SERVER_ERROR);
        } finally {
            FileUtils.tryToClose(outStream);
        }
    }