JSON对象中获取指定key的值

    平时处理Json对象时,想获取JSON对象中指定key的值,如下图,想直接取到"result"、"status"的值。

{

 "code": 0,

    "message": "ok",

    "body": {

        "result": "success",

        "status": "1"

    }

}

下面以get类型http请求示例详细说明:

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 调用xx处理任务
 * @author by dujiajun
 * @date 2021/1/20.
 */
public class JsonTest{

    private final String url ;
    public JsonTest(String owlUrl) {
        super("调用xx处理任务");
        this.url=owlUrl;
    }

    /**
     * 调用xx处理任务
     * @param url
     * @return
     */
    public int doGet(String url) throws Exception{
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse =null;
        String strResult = "";
        int rStatus = 3;
        try {
            //创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            //创建httpGet远程连接实例
            HttpGet httpGet =new HttpGet(url);
            // 设置请求头信息,鉴权
            //httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).//连接主机服务器时间
                    setConnectionRequestTimeout(20000).//请求超时时间
                    setSocketTimeout(20000).//数据读取超时时间
                    build();
            //为httpGet实例设置配置信息
            httpGet.setConfig(requestConfig);
            //通过get请求得到返回对象
            httpResponse = httpClient.execute(httpGet);

            //发送请求成功并得到响应
            if(httpResponse.getStatusLine().getStatusCode()==200){
                strResult = EntityUtils.toString(httpResponse.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(strResult);

                String result = jsonObject.getJSONObject("body").getString("result");
                String status = jsonObject.getJSONObject("body").getString("status");

                if(result.equalsIgnoreCase("success")){
                    if(status.equalsIgnoreCase("1")){
                        taskLogger.info("{%s}请求成功!",url);
                        rStatus = 1;
                    }else if(status.equalsIgnoreCase("2")) {
                        taskLogger.info("{%s}请求已被调用,请不要重复调用!",url);
                        rStatus = 2;
                    }
                }
            }else{
                taskLogger.error("请求{%s}失败,状态码为{%d}",url,httpResponse.getStatusLine().getStatusCode());
                rStatus = 3;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException i){
            i.printStackTrace();
            taskLogger.error("IOException异常:{%s}",i.getMessage());
       } finally {
            if(httpResponse!=null){
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient!=null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return rStatus;
    }


    public static void main(String args[]) throws Exception {
        String url ="http://xx.xx.xx.xx:9090/global/createTask".trim();
        JsonTest step =new JsonTest(url);
        step.taskLogger = LoggerFactory.getLogger(JsonTest.class.getName());
        for(int i=1;i<=3;i++){
            if(step.doGet(url)!=3){
                break;
            }else{
                i++;
            }
        }
    }
}
进行http请求后,获取到JSONObject后,使用以下两句即可获取"result"与"status" 两key的值。

String result = jsonObject.getJSONObject("body").getString("result");
String status = jsonObject.getJSONObject("body").getString("status");

 如觉得对你有帮助,请记得点个赞,个人整理不易....

你可能感兴趣的:(JAVA,java,http)