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");

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

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要替换多层级Json数据指定key,可以使用Json.NET库或者System.Text.Json的方法,以下是使用Json.NET库的示例: ```csharp using Newtonsoft.Json.Linq; // 假设原始的Json数据为 var jsonString = "{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"state\":\"NY\"}}"; // 将Json字符串转换为JObject对象 var jObject = JObject.Parse(jsonString); // 替换指定key jObject["address"]["state"] = "CA"; // 将JObject对象转换为Json字符串 var newJsonString = jObject.ToString(); ``` 在上面的代码,首先将原始的Json字符串转换为JObject对象,然后使用方括号运算符[]来访问指定key,并通过多级访问来访问嵌套的对象key,并将其替换为新的,最后将JObject对象转换为Json字符串。 如果使用System.Text.Json库,可以使用JsonDocument类和JsonElement类型来访问Json数据,并使用JsonElement类型的来修改指定key,以下是一个示例: ```csharp using System.Text.Json; // 假设原始的Json数据为 var jsonString = "{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"state\":\"NY\"}}"; // 将Json字符串转换为JsonDocument对象 var jsonDocument = JsonDocument.Parse(jsonString); // 获取根元素 var rootElement = jsonDocument.RootElement; // 替换指定key rootElement.GetProperty("address").GetProperty("state").SetString("CA"); // 将JsonDocument对象转换为Json字符串 var newJsonString = jsonDocument.RootElement.GetRawText(); ``` 在上面的代码,首先将原始的Json字符串转换为JsonDocument对象,然后使用GetProperty方法获取指定key,并使用多级访问来访问嵌套的对象key,并使用SetString方法将其替换为新的,最后将JsonDocument对象转换为Json字符串。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值