String和JSONObject的相互转换

1、由String类型的params转换为JSONObject

// params为String类型
JSONObject paramJson = JSONObject.fromObject(params);

//拿到这个JsonObject中token的值
paramJson.getString("token");

//获取int类型
paramJson.getInt("id");

//Boolean类型 判断是否存在该字段
paramJson.containsKey("resCode");

//当json中存在一个JSONObject时,用getJSONObject
(如
{
    "data":{
              "orderId":"xxxxxxxxxxx",
              "customerOrderId":"xxxxxxxxxxxxx"
           }
}
)

JSONObject dataJson = paramJson.getJSONObject("data");
dataJson.getString("orderId");
// 取出httprequest中的参数
String reqJson = HttpUtil.getStringByRequest(request);
JSONObject requestJson = JSONObject.fromObject(reqJson);

// 取出jsonObject中key为"params"、"signature"的参数
String params = requestJson.getString("params");
String signature = requestJson.getString("signature");

2、JsonObject转换为String

JSONObject parameter = new JSONObject();
parameter.put("customerOrderId", orderBean.getCustomerOrderId());
String params = parameter.toString();

3、Object转换为String

// value为Object(使用了gson的toJson方法)
String stringValue = gson.toJson(value);

4、String转换为Object

// redis中拿到String类型的参数
String orderJson = redisCache.getStringCache(phone).get();
if (orderJson == null) {
    logger.info("Cancel Failure: OrderInfo not found. {token}:{}", token);
    return ResultStatesEnum.PARAMS_ERROR.toMap();
}
ObjectMapper objectMapper = new ObjectMapper();
OrderInfo orderInfo = objectMapper.readValue(orderJson, OrderInfo.class);
OrderBean orderBean = new OrderBean();
orderBean.setCustomerOrderId(orderInfo.getCustomerOrderId());

猜你喜欢

转载自blog.csdn.net/Ay_Ly/article/details/88788452
今日推荐