以调用微信获取手机号api为例
微信官方api的返回值如下:
{
"errcode":0,
"errmsg":"ok",
"phone_info": {
"phoneNumber":"xxxxxx",
"purePhoneNumber": "xxxxxx",
"countryCode": 86,
"watermark": {
"timestamp": 1637744274,
"appid": "xxxx"
}
}
}
开发中可能只需要获取其中的phoneNumber这个字段,但获取的返回值一般是转换成了json字符串是String类型。
处理方法
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode jsonNode = mapper.readTree(resutlStr);
JsonNode phone_info = jsonNode.get("phone_info");
if (phone_info != null){
JsonNode phoneNumberJsonNode = phone_info.get("phoneNumber");
//解析出手机号
String phoneNumber = mapper.readValue(phoneNumberJsonNode.toString(), String.class);
}
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}